How to get path of an element in lxml?

Posted on

Question :

How to get path of an element in lxml?

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

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

Asked By: Fluffy


Answer #1:

Use getpath from ElementTree objects.

from lxml import etree
root = etree.fromstring('''
tree = etree.ElementTree(root)
for e in root.iter():


Answered By: nosklo

Answer #2:

See the Xpath and XSLT with lxml from the lxml documentation This gives the path of the element containg the text

An example would be

import cStringIO
from lxml import etree

f = cStringIO.StringIO('<foo><bar><x1>hello</x1><x1>world</x1></bar></foo>')
tree = lxml.etree.parse(f)
find_text = etree.XPath("//text()")

# and print out the required data
print [tree.getpath( text.getparent()) for text in find_text(tree)]

# answer I get is 
>>> ['/foo/bar/x1[1]', '/foo/bar/x1[2]']
Answered By: mmmmmm

Answer #3:

If all you have in your section of code is the element and you want the element’s xpath do then element.getroottree().getpath(element) will do the job.

from lxml import etree

xml = '''
tree = etree.fromstring(xml)

for element in tree.iter():
    print element.getroottree().getpath(element)
Answered By: shrewmouse

Answer #4:

root = etree.parse(open('tmp.txt'))

for e in root.iter():
    print root.getpath(e)
Answered By:

Leave a Reply

Your email address will not be published.