You can scrape Google Finance using BeautifulSoup
web scraping library without the need to use selenium
as the data you want to extract doesn't render via Javascript. Plus it will be much faster than launching the whole browser.
Check code in online IDE.
from bs4 import BeautifulSoup
import requests, lxml, json
params = {
"hl": "en"
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36",
}
html = requests.get(f"https://www.google.com/finance?q=tsla)", params=params, headers=headers, timeout=30)
soup = BeautifulSoup(html.text, "lxml")
ticker_data = []
for ticker in soup.select('.tOzDHb'):
title = ticker.select_one('.RwFyvf').text
price = ticker.select_one('.YMlKec').text
index = ticker.select_one('.COaKTb').text
price_change = ticker.select_one("[jsname=Fe7oBc]")["aria-label"]
ticker_data.append({
"index": index,
"title" : title,
"price" : price,
"price_change" : price_change
})
print(json.dumps(ticker_data, indent=2))
Example output
[
{
"index": "Index",
"title": "Dow Jones Industrial Average",
"price": "32,774.41",
"price_change": "Down by 0.18%"
},
{
"index": "Index",
"title": "S&P 500",
"price": "4,122.47",
"price_change": "Down by 0.42%"
},
{
"index": "TSLA",
"title": "Tesla Inc",
"price": "$850.00",
"price_change": "Down by 2.44%"
},
# ...
]
There's a scrape Google Finance Ticker Quote Data in Python blog post if you need to scrape more data from Google Finance.