获取lxml节点中的所有文本



我使用以下方法打印元素节点内的所有文本(不是html,而是实际包含的文本(:

''.join(node.xpath('//div[@class="title_wrapper"]')[0].itertext())

有没有更干净的方法来做这件事?

您可以使用XPath的string()函数。

如果混合内容中有大块空白,可以使用XPath的normalize-space()函数。

三个例子(你和我的两个(。。。

Python

from lxml import etree
xml = """<doc>
<div class="title_wrapper">Some text. Some <span>more</span> text. 
<span>Even <span>m<span>o</span>re</span> text!</span>
</div>
</doc>"""
tree = etree.fromstring(xml)
print(''.join(tree.xpath('//div[@class="title_wrapper"]')[0].itertext()))
print(tree.xpath('string(//div[@class="title_wrapper"])'))
print(tree.xpath('normalize-space(//div[@class="title_wrapper"])'))

输出

Some text. Some more text. 
Even more text!
Some text. Some more text. 
Even more text!
Some text. Some more text. Even more text!

最新更新