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.
lxml. etree supports the simple path syntax of the find, findall and findtext methods on ElementTree and Element, as known from the original ElementTree library (ElementPath).
lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.
lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With