我构建了一个小脚本,该脚本应该在页面中找到一些特定的字符串并返回包含该字符串的元素的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]返回<Element b at 0x7f034a08e940>,我仍然不知道如何找到该元素的XPath。
result[0]
<Element b at 0x7f034a08e940>
我想要的字符串是:
/html/body/div[4]/div/div[2]/div[2]/div[1]/div/ul/li[2]
您可以使用getpath()从获取xpath element,例如:
getpath()
element
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