首页 > 解决方案 > 如何访问路径响应

问题描述

我试图从雅虎财经那里抢到股价。我不太了解 Xpaths,所以我不知道如何访问返回的值

from lxml import html
import requests

r = requests.get('https://uk.finance.yahoo.com/quote/BVXP.L?p=BVXP.L')
root = html.fromstring(r.content)
price = root.xpath('//*[@id="quote-header-info"]/div[3]/div/div/span[1]')

我已经在 chrome 中使用 XpathHelper 检查了 xpath,它返回了我正在寻找的值(3,325.00 - 或者当时的报价。)

但是在 Python 中,我不知道如何访问该信息。

print(price)
# Returns [<Element span at 0x108832278>]

正确的做法是什么?

标签: pythonlxml

解决方案


尝试print(price[0].text),您会看到 price 是一个包含一个项目的列表,只需通过索引我们就可以访问您想要的信息。

仅供参考,如果您遇到困难,请始终尝试查看它拥有的方法,print(dir(price[0]))这只是您示例中的一个说明,但仅通过查看对象的方法和属性,它就可以让我们一瞥,前进的方向。


推荐阅读