大家好,我想在 scrapy 中使用 xpath 从 html block 中提取所有文本
假设我们有这样一个 block :
<div>
<p>Blahblah</p>
<p><a>Bluhbluh</a></p>
<p><a><span>Bliblih</span></a></p>
</div>
我想将文本提取为 ["Blahblah","Bluhbluh","Blihblih"]。我希望 xpath 递归地在 div 节点中查找文本。
我听说尝试过://div/p[descendant-or-self::*]/text()
但它不提取嵌套元素。
干杯! 塞布
最佳答案
您可以在每个 p
元素上使用 XPath 的 string()
函数:
>>> import scrapy
>>> selector = scrapy.Selector(text="""<div>
... <p>Blahblah</p>
... <p><a>Bluhbluh</a></p>
... <p><a><span>Bliblih</span></a></p>
... </div>""")
>>> [p.xpath("string()").extract() for p in selector.xpath('//div/p')]
[[u'Blahblah'], [u'Bluhbluh'], [u'Bliblih']]
>>> import operator
>>> map(operator.itemgetter(0), [p.xpath("string()").extract() for p in selector.xpath('//div/p')])
[u'Blahblah', u'Bluhbluh', u'Bliblih']
>>>
关于html - 提取文本 xpath scrapy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26301831/