Skip to content Skip to sidebar Skip to footer

Import Yahoo Finance Stock Price With Beautifulsoup And Request

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.7

Solution 1:

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)

Outputs:

2,477.83

The only change is this line in your code:

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

to

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

Post a Comment for "Import Yahoo Finance Stock Price With Beautifulsoup And Request"