Next / Previous / Contents / Shipman's homepage

9.7. Element.findtext(): Extract text content

To find the text content inside a specific element, call this method, where E is some ancestor of that element:

E.findtext(path, default=None, namespaces=N)

The path argument specifies the desired element in the same way as does the path argument in Section 9.5, “Element.find(): Find a matching sub-element”.

Here's a conversational example.

>>> from lxml import etree
>>> node=etree.fromstring('<a><b>bum</b><b>ear</b><c/></a>')
>>> node.findtext('b')
'bum'
>>> node.findtext('c')
''
>>> node.findtext('c', default='Huh?')
''
>>> print node.findtext('x')
None
>>> node.findtext('x', default='Huh?')
'Huh?'

The optional namespaces keyword argument allows you to specify namespace prefixes for multi-namespace documents; for details, see Section 9.5, “Element.find(): Find a matching sub-element”.