python - find xpath of element containing string

别说谁变了你拦得住时间么 提交于 2019-12-30 10:34:49

问题


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:


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


来源:https://stackoverflow.com/questions/29890301/python-find-xpath-of-element-containing-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!