Extracting S&P 500 Index Data in Real-Time
In this lesson, we will learn how to extract S&P 500 stock data from Yahoo Finance.
1. Fetching the Current Price
current_price_element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span[data-testid="qsp-price"]'))) current_price = current_price_element.text
find_element() is used to find a specific element on the page.
The XPATH is defined as follows:
-
div[contains(@class, 'price')] :
divtag that containspriceclass -
fin-streamer[contains(@class, 'livePrice')] :
fin-streamertag that containslivePriceclass -
span :
spantag
In summary, the XPATH selects elements with div tags containing the price class, fin-streamer tags containing the livePrice class, and finally the span tag.
2. Fetching the Previous Close Value
previous_close_element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'fin-streamer[data-field="regularMarketPreviousClose"]'))) previous_close = previous_close_element.text
By.CSS_SELECTOR is used to select the fin-streamer tag with the data-field="regularMarketPreviousClose" attribute.
The XPATH is defined as follows:
- fin-streamer[data-field="regularMarketPreviousClose"] :
fin-streamertag with thedata-field="regularMarketPreviousClose"attribute
The previous_close_element stores the element containing the Previous Close value.
previous_close_element.text retrieves the Previous Close value as text.
3. Fetching the Volume Value
volume_element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'fin-streamer[data-field="regularMarketVolume"]'))) volume = volume_element.text
We select the fin-streamer tag with the data-field="regularMarketVolume" attribute to fetch the Volume value.
volume_element.text retrieves the Volume value as text.
Lessons in this chapter ยท Practical Web Crawling
- 1. Extracting Article Titles from BBC News
- 2. Saving Extracted Article Data to a CSV File
- 3. Real-Time Stock Data Collection from Yahoo Finance
- 4. Extracting S&P 500 Index Data in Real-Time
- 5. Saving Extracted Data as a CSV File with Selenium
- 6. Automating Data Research with Web Scraping
- 7. Saving Collected Data as a CSV File
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help