Issue
I tried to scrape the stock price from https://finance.yahoo.com/quote/TSLA/ using BeautifulSoup, but for some reason my program doesn't print the stock price and instead returns "None". How do I correctly scrape the stock price? My code:
from bs4 import BeautifulSoup
import requests
import time
headers = {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36"}
url = "https://finance.yahoo.com/quote/TSLA/"
time.sleep(10)
GetUrl = requests.get(url)
soup = BeautifulSoup(GetUrl.text)
StockPrice = soup.find({"Fw(b) Fz(36px) Mb(-4px) D(ib)"})
print(StockPrice)
Here is the place that I found the data, which I copied to soup.find().
Solution
In soup.find()
, use the class_=
parameter:
import requests
from bs4 import BeautifulSoup
url = "https://finance.yahoo.com/quote/TSLA/"
GetUrl = requests.get(url)
soup = BeautifulSoup(GetUrl.text, "html.parser")
# use class_="..."
StockPrice = soup.find(class_="Fw(b) Fz(36px) Mb(-4px) D(ib)")
print(StockPrice.text)
Prints:
975.93
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.