Web Scraping Stock Ticker Price from Yahoo Finance using BeautifulSoup

2024/10/8 13:30:58

I'm trying to scrape Gold stock ticker from Yahoo! Finance.

from bs4 import BeautifulSoup
import requests, lxmlresponse = requests.get('https://finance.yahoo.com/quote/GC=F?p=GC=F')
soup = BeautifulSoup(response.text, 'lxml')
gold_price = soup.findAll("div", class_='My(6px) Pos(r) smartphone_Mt(6px)')[2].find_all('p').text

Whenever I run this it returns: list index out of range. When I do print(len(ssoup)) it returns 4.

Any ideas? Thank you.

Answer

You can make a direct request to the yahoo server. To locate the query URL you need to open Network tab via Dev tools (F12) -> Fetch/XHR -> find name: spark?symbols= (refresh page if you don't see any), find the needed symbol, and see the response (preview tab) on the newly opened tab on the right.

You can make direct requests to all of these links if the request method is GET since POST methods are much more complicated.

You need json and requests library, no need for bs4. Note that making a lot of such requests might block your IP (or set an IP rate limit) or you won't get any response because their system might detect that it's a bot since the regular user won't make such requests to the server, repeatedly. So you need to figure out how to bypass it.

Update: There's possibly a hard limit on how many requests can be made in an X period of time.


Code and example in the online IDE (contains full JSON response):

import requests, jsonresponse = requests.get('https://query1.finance.yahoo.com/v7/finance/spark?symbols=GC%3DF&range=1d&interval=5m&indicators=close&includeTimestamps=false&includePrePost=false&corsDomain=finance.yahoo.com&.tsrc=finance').text
data_1 = json.loads(response)gold_price = data_1['spark']['result'][0]['response'][0]['meta']['previousClose']
print(gold_price)# 1830.8

P.S. There's a blog about scraping Yahoo! Finance Home Page of mine, which is kind of relevant.

https://en.xdnf.cn/q/118692.html

Related Q&A

How to convert the radius from meter to pixel?

I have a camera with these specs:full resolution 1280x1024 pixel size 0.0048mm focal length 8 mmI need to detect a ball in this image. It is 4 meters away and its radius is 0.0373 meter. How to convert…

Calculting GPA using While Loop (Python)

A GPA, or Grade point Average, is calculated by summing the grade points earned in a student’s courses and then dividing by the total units. The grade points for an individual course are calculated by…

Return function that modifies the value of the input function

How can I make a function that is given a function as input and returns a function with the value tripled. Here is some pseudo code for what Im looking for. Concrete examples in Python or Scala would b…

how to access the list in different function

I have made a class in which there are 3 functions. def maxvalue def min value def getActionIn the def maxvalue function, I have made a list of actions. I want that list to be accessed in def getaction…

Replacing numpy array with max value [duplicate]

This question already has answers here:numpy max vs amax vs maximum(4 answers)Closed 2 years ago.I have an array, a = np.array([[0,9,8],[5,6,4]])how to replace the each array in axis 1 with the max val…

Finding the max and min in dictionary as tuples python

so given this dictionary im trying to find the max value and min value {Female :[18,36,35,49,19],Male :[23,22,6,36,46]}the output should be in tuples for example key: (min,max)Female: (18,49) Male: (6,…

Flask sqlalchemy relations across multiple files

Im new to Flask Sqlalchemy and I want to declare multiple models and relate them to each other, I followed the example in the documentation but I keep getting this error sqlalchemy.exc.InvalidRequestEr…

Parsing XML with Pykml

I have the following xml file I got from QGIS<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.…

Python Google App Engine Receiving a string in stead of JSON object

I am sending a HTTP POST request from android to a server using the script belowURI website = new URI("http://venkygcm.appspot.com");HttpClient client = new DefaultHttpClient();HttpPost reque…

Creating Gui for python client server

Help needed with my python project. Unable to get the code for the client or server implemented with the Gui i created. it is one based on book seller where the client is the buyer and the server is th…