Xpath 中没有带 lxml 的元素:Javascript 生成的页面

No Element in Xpath with lxml : Javascript Generated Page

我之前让 Xpath 与其他东西一起工作,在 Chrome 浏览器中,我可以在控制台中使用 $x('//*[@id="profile"]/ 找到我的 xpath div[2]/div[2]/div[1]/div[2]/div[2]/div [1]/span[2]) 在 https://pubgtracker.com/profile/pc/Fuzzyllama/duo?region=na.

当我尝试在代码中获取此元素时,它 returns 是一个空数组,有人知道为什么吗?

@client.command(pass_context=True)
async def checkChrisPubg(ctx):
    page = requests.get('https://pubgtracker.com/profile/pc/Fuzzyllama/duo?region=na')
    tree = html.fromstring(page.content)
    duoRank = tree.xpath('//*[@id="profile"]/div[2]/div[2]/div[1]/div[2]')
    print(duoRank)

print(duoRank) 给我 []

您使用什么库作为解析器?

如果xml.etree.ElementTree,

ElementTree provides limited support for XPath expressions. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the core library.

http://effbot.org/zone/element-xpath.htm

所以,我尝试用 PyQt4 来做这个,但在实践中没有真正成功,一个更简单但更具侵入性的解决方案是使用 Selenium,一个用于加载网页的网络驱动程序。

我确信对此有多种解决方案,但在我找到解决方案之前我经历了一段地狱般的时光甚至知道出了什么问题。

当使用 lxml 时,您应该确保您尝试获取的数据 不是由 javascript 生成的。为此,您可以打开Chrome开发人员工具单击菜单(3 个垂直点),转到设置转到底部禁用Javascript重新加载页面.

如果什么都没有页面生成的内容为Javascript

下面是一个简单的解决方案,这将等待页面呈现,然后让您使用 lxml 解析树。

此解决方案将要求您使用这些导入(您必须安装 selenium):

from selenium import webdriver

现在,您可以加载页面并开始抓取:

#Load in your browser(I use chrome)
browser = webdriver.Chrome()
#Choose url you want to scrape
url = 'https://pubgtracker.com/profile/pc/Fuzzyllama/duo?region=na'
#get the url with Selenium
browser.get(url)
#get the innerhtml from the rendered page
innerHTML = browser.execute_script("return document.body.innerHTML")

#Now use lxml to parse the page
tree = html.fromstring(innerHTML)
#Get your element with xpath
duoRank = tree.xpath('//*[@id="profile"]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/span[2]/text()')
#close the browser
browser.quit()

我最初的解决方案本来不错,但没有用,因为其中大部分已被弃用。

打开页面源代码 view-source:https://pubgtracker.com/profile/pc/Fuzzyllama/duo?region=na 这里是 script 和 json playerData 在第 491[=16= 行].解析一下。