我构建了一个小脚本,它应该在页面中找到一些特定的字符串并返回包含该字符串的元素的xpath.
目的是使用此xpath来查找具有相同上下文的字符串.
我正在使用此代码:
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]返回<元素b在0x7f034a08e940>无论如何我无法弄清楚如何找到这个元素的XPath.
我想要的字符串是:
/html/body/div[4]/div/div[2]/div[2]/div[1]/div/ul/li[2]
解决方法:
您可以使用getpath()
从元素获取xpath,例如:
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))
输出:
/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