<span rel="v:addr">
<span property="v:region">
<a href="https://tabelog.com/en/tokyo/">
123
</a>
</span>
<span property="v:locality">
<a href="https://tabelog.com/en/tokyo/A1317/A131710/rstLst/">
456
</a>
<a href="https://tabelog.com/en/rstLst/">
789
</a>
10
</span>
<span property="v:street-address">
</span>
</span>
我想提取 span 标记内的文本,不带任何空格,并将其作为末尾的一个字符串。
我想要这个结果:
12345678910
这是我的代码:
'AddressLocalityJap':"".join(response.xpath('normalize-space(//*[@id="anchor-rd-detail"]/section[1]/table/tbody/tr[4]/td/p[2]/span/span[2]//text()').extract())
最佳答案
可以通过//span/span
获取所有span。并使用 text_content()
获取每个范围中的文本。并使用正则表达式替换所有空白字符。
import re
from lxml import html
tree = html.fromstring(html_source)
span = tree.xpath("//span/span", smart_strings=0)
text = ''.join([re.sub(r"\s+", '', item.text_content()) for item in span])
关于python - 如何使用 XPath 提取同一标签下的所有文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44915686/