0

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"

and

data-reactid="35".

When I change to 35, it fails. 36 works but only show % change. I want stock price, not % change.

thanks for your help!

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)
Dan-Dev
  • 8,957
  • 3
  • 38
  • 55
New_Py_Guy
  • 53
  • 1
  • 7

1 Answers1

2

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")
Dan-Dev
  • 8,957
  • 3
  • 38
  • 55