获取lxml节点中的所有文本

时间:2018-11-07 18:51:29

标签: python lxml

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

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

是否有一种更清洁的方法?

1 个答案:

答案 0 :(得分:1)

您可以使用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!