https://next.newsimpact.com/NewsWidget/Live
我正在尝试编写一个 python 脚本,该脚本将从上面链接中的 HTML 表中获取值。上面的链接是我试图从中获取的网站,这是我编写的代码。我认为我的 XPath 可能不正确,因为它在其他元素上表现良好,但我使用的路径没有返回/打印任何内容。
from lxml import html
import requests
page = requests.get('https://next.newsimpact.com/NewsWidget/Live')
tree = html.fromstring(page.content)
#This will create a list of buyers:
value = tree.xpath('//*[@id="table9521"]/tr[1]/td[4]/text()')
print('Value: ', value)
奇怪的是,当我打开查看源代码页时,我找不到我想要从中提取的表。 感谢您的帮助!
最佳答案
初始页面源中缺少所需数据 - 它来自 XHR。您可以通过以下方式获取:
import requests
response = requests.get('https://next.newsimpact.com/NewsWidget/GetNextEvents?offset=-120').json()
first_previous = response['Items'][0]['Previous'] # Current output - "2.632"
second_previous = response['Items'][1]['Previous'] # Currently - "0.2"
first_forecast = response['Items'][0]['Forecast'] # ""
second_forecast = response['Items'][1]['Forecast'] # "0.3"
您可以将response
解析为简单的Python字典并获取所有必需的数据
关于python - 从 HTML 文档获取 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48875330/