<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])
