2014-01-30 31 views
0

这是我的示例html代码。如何使用xpath解析嵌套的html标记

使用HtmlXpathSelector我需要解析html文件。

DEF解析(个体,响应): edxData = HtmlXpathSelector(响应)

  1. 第一我需要得到所有包含 edxData.xpath标记('// H2 [@class =“标题课程标题“]')
  2. 里面的标签我需要检查一个标签值。
  3. 然后需要使用类名称字幕course-subtitle copy-detail解析div标签。 如何可以解析这个值好心给一些建议

样本HTML响应数据:

遍历内标签
<html> 
<body> 
<h2 class="title course-title"> 
<a href="https://www.edx.org/course/mitx/mitx-14-73x-challenges-global-poverty-1350">The Challenges of Global Poverty 
</a> 
</h2> 
<div class="subtitle course-subtitle copy-detail">A course for those who are interested in the challenge posed by massive and persistent world poverty. 
</div> 
</body> 
</html> 

回答

1

一种方式可以是:

>>> for h2 in sel.xpath('//h2[@class = "title course-title"]'): 
...  print h2.xpath('a') 
... 
[<Selector xpath='a' data=u'<a href="https://www.edx.org/course/mitx'>] 

甚至根本:

>>> sel.xpath('//h2[@class = "title course-title"]/a') 
[<Selector xpath='//h2[@class = "title course-title"]/a' data=u'<a href="https://www.edx.org/course/mitx'>] 

找到另一个XPath的,简单地做:

>>> sel.xpath('//div[@class="subtitle course-subtitle copy-detail"]') 
[<Selector xpath='//div[@class="subtitle course-subtitle copy-detail"]' data=u'<div class="subtitle course-subtitle cop'>] 

它看起来像你使用scrapy,请还标记了这个问题这样