How to parse yahoo finance stock price using beautifulsoup?

Viewed 418

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

enter image description here

1 Answers

The tag is <span>, not <div>:

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")


print(soup.find_all("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"))

Prints:

[<span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="32">134.36</span>]

EDIT: To get only number:

print(
    soup.find("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").text
)

Prints:

134.23
Related