Reputation: 17144
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)
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)")
Upvotes: 2
Views: 1562
Reputation: 195408
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
Upvotes: 1