python - 从 HTML 文档获取 XPath

标签 python html xpath python-requests

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/

相关文章:

python - 无法使用executemany一次插入多列

python - 使用 python 订阅 ROS sensor_msg/Image

javascript - 如何切换具有持续时间和显示的 jQuery 元素?

jquery - Overlay div - 滚动尽可能多的内容

python - 如何使用两个变量迭代 xpath?

python - 可能是 python 中的简单列表操作

python - 在Python中将不规则间隔的数据重新采样为规则网格

javascript - 从 anchor 标签href url调用js函数

python - scrapy 带有换行符和嵌套标签

=importXML() 中的 xpath 用于提取元描述