【问题标题】:How to get the text from child nodes if it is parents to other node in Scrapy using XPath如果它是使用 XPath 在 Scrapy 中的其他节点的父节点,如何从子节点获取文本
【发布时间】:2014-12-25 04:58:27
【问题描述】:

我面临一个问题,我必须从子节点获取结果,该子节点可能是也可能不是在 scrapy 中使用 Xpath 的其他节点的父节点。考虑这种情况

<h1 class="main">
 <span class="child">data</span>
</h1>

<h1 class="main">
<span class="child">
 <span class="child2">data</span>
</span>
</h1>

我的解决方案是response.xpath(".//h1[@class='main']/span/text()").extract()

【问题讨论】:

    标签: python html xpath scrapy


    【解决方案1】:

    使用//text,它将从您的span 中返回列表中的所有文本元素,包括父项和子项:

    response.xpath(".//h1[@class='main']/span//text()").extract()
    

    【讨论】:

    • @PramodBisht,如果我的回答可以帮助您解决问题。请接受我的回答/点赞:)
    • 投票至少需要 15 分,我是初学者,只有 1 分。希望你能理解。
    • @PramodBisht,感谢 :)
    【解决方案2】:

    你可以使用:

    • response.xpath("string(.//h1[@class='main']/span)").extract()
    • 甚至response.xpath("string(.//h1[@class='main'])").extract(),如果您关注的是整个标题文本

    【讨论】:

      猜你喜欢
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多