进口雅虎金融股票价格与beautifulsoup和要求 [英] import yahoo finance stock price with beautifulsoup and request
问题描述
因此,我有一个检查股价的脚本.雅虎改变了一些东西,现在我得到了%的变化,而不是股价.以下是原始脚本.运行它时,我得到的是"+0.70(+ 0.03%)",而不是2477.83.我真正看到的唯一区别是:
So I have an script that check stock prices. Yahoo change something and now I get the % change rather than the stock price. Below is the original script. When I run it, I get "+0.70 (+0.03%)", rather than 2,477.83. The only difference I really see is:
data-reactid ="36"
data-reactid="36"
和
data-reactid ="35".
data-reactid="35".
当我更改为35时,它会失败. 36件作品,但只显示%变化.我要的是股价,而不是涨跌幅.
When I change to 35, it fails. 36 works but only show % change. I want stock price, not % change.
感谢您的帮助!
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)
推荐答案
有不止一个span元素,其data-reactid ="35"属性,因此请通过class属性选择所需的一个.
There is more than one span element with the attribute data-reactid = "35" so select the one you want by the class attribute.
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
唯一的变化是代码中的这一行:
The only change is this line in your code:
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")
这篇关于进口雅虎金融股票价格与beautifulsoup和要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!