【问题标题】:how to parse nested html tag using xpath如何使用 xpath 解析嵌套的 html 标签
【发布时间】:2014-02-22 23:02:02
【问题描述】:

这是我的示例 html 代码。

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

def 解析(自我,响应): edxData = HtmlXpathSelector(响应)

  1. 首先我需要获取所有包含 edxData.xpath('//h2[@class= "title course-title"]')
  2. 在那个标签里面我需要检查一个标签值。
  3. 然后需要解析带有类名subtitle 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>  

【问题讨论】:

    标签: html xpath scrapy


    【解决方案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,请也标记该问题

    【讨论】:

      猜你喜欢
      • 2012-05-26
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      相关资源
      最近更新 更多