How to get text for a root element using lxml?
lxml, python
Solution
from lxml import etree
XML = '<some_tag class="abc"><strong>Hello</strong> World</some_tag>'
some_tag = etree.fromstring(XML)
for element in some_tag:
print element.tag, element.text, element.tail
Output:
strong Hello World
For information on the `.text` and `.tail` properties, see:
- http://lxml.de/tutorial.html#elements-contain-text
- http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/etree-view.html
To get exactly the result that you expected, use
print etree.tostring(some_tag.find("strong"))
Output:
<strong>Hello</strong> World
Problem
I'm completely stumped why lxml `.text` will give me the text for a child tag but for the root tag. ``` some_tag = etree.fromstring('<some_tag class="abc"><strong>Hello</strong> World</some_tag>') some_tag.find("strong") Out[195]: <Element strong at 0x7427d00> some_tag.find("strong").text Out[196]: 'Hello' some_tag Out[197]: <Element some_tag at 0x7bee508> some_tag.text ``` `some_tag.find("strong").text` returns the text between the `<strong>` tag. I expect `some_tag.text` to return everything between `<some_tag> ... </some_tag>` Expected: ``` <strong>Hello</strong> World ``` Instead, it returns nothing.