6

I build a small script that supposed to find some specific string in a page and return the xpath of the element containing this string. The purpose is to use this xpath for finding string with same context.

I'm using this code:

import requests
from lxml import html
page = requests.get("http://www.w3schools.com/xpath/")
tree = html.fromstring(page.text)
result = tree.xpath('//*[. = "XML"]')

result[0] returns <Element b at 0x7f034a08e940> and I can't figure out how to find this element's XPath anyway .

The string I would like to have is:

/html/body/div[4]/div/div[2]/div[2]/div[1]/div/ul/li[2]
1

1 Answer 1

10

You can use getpath() to get xpath from element, for example :

import requests
from lxml import html

page = requests.get("http://www.w3schools.com/xpath/")
root = html.fromstring(page.text)
tree = root.getroottree()
result = root.xpath('//*[. = "XML"]')
for r in result:
    print(tree.getpath(r))

Output :

/html/body/div[3]/div/ul/li[10]
/html/body/div[3]/div/ul/li[10]/a
/html/body/div[4]/div/div[2]/div[2]/div[1]/div/ul/li[2]
/html/body/div[5]/div/div[6]/h3
/html/body/div[6]/div/div[4]/h3
/html/body/div[7]/div/div[4]/h3
Sign up to request clarification or add additional context in comments.

1 Comment

I tried your code with URL : w3schools.com/xml/xpath_intro.asp. Actually there are 8 elements include XML string but script returns only 7 Element. Maybe because of the Panel?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.