How to get path of an element in lxml?

Fluffy picture Fluffy · Oct 16, 2009 · Viewed 32.4k times · Source

I'm searching in a HTML document using XPath from lxml in python. How can I get the path to a certain element? Here's the example from ruby nokogiri:

page.xpath('//text()').each do |textnode|
    path = textnode.path
    puts path
end

print for example '/html/body/div/div[1]/div[1]/p/text()[1]' and this is the string I want to get in python.

Answer

nosklo picture nosklo · Oct 16, 2009

Use getpath from ElementTree objects.

from lxml import etree
    
root = etree.fromstring('''
    <foo><bar>Data</bar><bar><baz>data</baz>
    <baz>data</baz></bar></foo>
    ''')
    
tree = etree.ElementTree(root)
for e in root.iter():
    print(tree.getpath(e))

Prints

/foo
/foo/bar[1]
/foo/bar[2]
/foo/bar[2]/baz[1]
/foo/bar[2]/baz[2]