Issue
For the learning purpose, I tried to extract the current stock price of AAPL using yahoo finance. However, I am getting empty outputs.
How to extract the stock value?
Required value: 134.69 (as shown in image below) (note this value changes with time, but this is just an example)
MWE
import numpy as np
import pandas as pd
import json
import requests
from bs4 import BeautifulSoup
ticker = 'aapl'
url = f"https://finance.yahoo.com/quote/{ticker.upper()}"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
soup.find_all("div", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")
Inspect
Solution
EDIT (13.06.2023): Updated to working version
To get current quote you can use next example (don't forget to set User-Agent
HTTP header to get right response from the server):
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/114.0'}
ticker = "AAPL"
url = f"https://finance.yahoo.com/quote/{ticker}"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
current = soup.select_one(f'fin-streamer[data-field="regularMarketPrice"][data-symbol="{ticker}"]')
print(current['value'])
Prints:
183.79
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.