使用 beautifulsoup 导入雅虎金融股票价格并请求

import yahoo finance stock price with beautifulsoup and request

所以我有一个检查股票价格的脚本。雅虎改变了一些东西,现在我得到的是百分比变化而不是股价。以下是原剧本。当我 运行 它时,我得到“+0.70 (+0.03%)”,而不是 2,477.83。我真正看到的唯一区别是:

data-reactid="36"

data-reactid="35".

当我更改为35时,它失败了。 36 有效但仅显示百分比变化。我想要股价,而不是百分比变化。

感谢您的帮助!

import urllib.request
from bs4 import BeautifulSoup


# S&P 500
page = urllib.request.urlopen("https://finance.yahoo.com/quote/%5EGSPC?p=^GSPC")
content = page.read().decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
valsp = soup.find("span", {"data-reactid": "36"}).decode_contents(formatter="html")
print(valsp)

有多个具有属性 data-reactid = "35" 的 span 元素,因此 select 您想要的 class 属性。

import urllib.request
from bs4 import BeautifulSoup

# S&P 500
page = urllib.request.urlopen("https://finance.yahoo.com/quote/%5EGSPC?p=^GSPC")
content = page.read().decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
# print (soup)
valsp = soup.find("span", {"data-reactid": "35", "class" : "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}).decode_contents(formatter="html")
print(valsp)

输出:

2,477.83

唯一的变化是代码中的这一行:

valsp = soup.find("span", {"data-reactid":"35"}).decode_contents(formatter="html")

valsp = soup.find("span", {"data-reactid": "35", "class" : "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}).decode_contents(formatter="html")