Get all text in an lxml node

Viewed 2893

I am using the following approach to print all the text (not html, but actual text contained) within an element node:

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

Is there a cleaner approach to doing this?

1 Answers

You could use XPath's string() function.

If you have large chunks of whitespace from mixed content, you could use XPath's normalize-space() function.

Example of all three (yours and my two)...

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

Output

Some text. Some more text. 
    Even more text!

Some text. Some more text. 
    Even more text!

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