【问题标题】:Matching multiple <p> tags in scrapy在scrapy中匹配多个<p>标签
【发布时间】:2015-12-08 21:46:12
【问题描述】:

我有类似以下html:

<div class="articleBody">
  <p>
    <strong>Text</strong> lorem ipsum... 
    <strong>lorem ipsum...</strong>
  </p>
  <p>lorem ipsum 
    <strong> lorem ipsum lorem ipsum</strong>
    lorem ipsum...lorem ipsum...lorem ipsum...lorem ipsum...
  </p>
</div>

以更一般的方式,我有一个&lt;p&gt; 标签列表,里面有几个&lt;strong&gt; 标签。

我想获取所有 &lt;p&gt; 标记的文本,减去 &lt;strong&gt; 标记...我的意思是“articleBody”div 类中的文本。

我拥有的是

response.xpath('string(//div[@class="articleBody"]//p)'.extract()

但这只会返回第一个&lt;p&gt;

任何帮助将不胜感激。

【问题讨论】:

  • 我不知道scrapy,但你应该能够通过使用//div[@class="articleBody"]/p/text() 来获取所有这些文本。 p.s 我可能误解了“减去 标签的含义。
  • Luciddream 是对的,或者如果您不关心 p 标签是否是 div[@class="articleBody"] 的直接子代,则使用 //p 而不是 /p。可以将所有内容转储到一个字符串中,例如:''.join(response.xpath('//div[@class="articleBody"]/p//text()').extract())

标签: python xpath scrapy


【解决方案1】:

试一试:

for node in response.xpath('//div[@class="articleBody"]//p'):
        print node.xpath('string()').extract()

...然后您可以连接您的字符串或将它们添加到列表或其他任何东西,而不是像我一样打印它们。

还有用于 xpath 2.0 的 string-join() 函数,但看起来 scrapy 支持 xpath 1.0。

更多关于字符串连接的信息在这里:http://www.w3.org/TR/xpath-functions/#func-string-join

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 2021-10-10
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2013-11-29
    • 2021-11-22
    • 2015-12-26
    相关资源
    最近更新 更多