Extracting text after tag in Python's ElementTree

mae picture mae · Mar 12, 2012 · Viewed 14.6k times · Source

Here is a part of XML:

<item><img src="cat.jpg" /> Picture of a cat</item>

Extracting the tag is easy. Just do:

et = xml.etree.ElementTree.fromstring(our_xml_string)
img = et.find('img')

But how to get the text immediately after it (Picture of a cat)? Doing the following returns a blank string:

print et.text

Answer

Charles Duffy picture Charles Duffy · Mar 12, 2012

Elements have a tail attribute -- so instead of element.text, you're asking for element.tail.

>>> import lxml.etree
>>> root = lxml.etree.fromstring('''<root><foo>bar</foo>baz</root>''')
>>> root[0]
<Element foo at 0x145a3c0>
>>> root[0].tail
'baz'

Or, for your example:

>>> et = lxml.etree.fromstring('''<item><img src="cat.jpg" /> Picture of a cat</item>''')
>>> et.find('img').tail
' Picture of a cat'

This also works with plain ElementTree:

>>> import xml.etree.ElementTree
>>> xml.etree.ElementTree.fromstring(
...   '''<item><img src="cat.jpg" /> Picture of a cat</item>'''
... ).find('img').tail
' Picture of a cat'