python lxml – use absolute xpath to find elements [solved]

When using lxml library, using an absolute xpath such as ‘/root/child/other_child’ end up with a nasty error message:

SyntaxError: cannot use absolute path on element

Reason for that is that call was performed on an Element using .findall() method.

To use an absolute xpath, do not perform call on an Element, rather perform call on an ElementTree and call .xpath() method instead of .findall()

Illustration below:

etree.parse(fpath).getroot().findall('/root/child/') # => SyntaxError: cannot use absolute path on element
etree.parse(fpath).xpath('/root/child/') # => OK

sources

Post a Comment

Your email is never published nor shared. You're allow to say what you want...