How To Fetch Stock Market Data Using Selenium Python

Stock Market Data Using Python Selenium

Getting the latest stock market data using Python offers a great use case scenario, both for analytical and price analysis. In this tutorial, we’ll learn how to get stock market data using python selenium.

For this particular tutorial, we’ll fetch data of BRITANNIA industries from NSE (National Stock Exchange of India) but our code can take any other company’s names as input and fetch its data as well.

You may also like: Fetch Data From a Webpage Using Selenium [Complete Guide]

Get Stock Market Data using Python

Let’s get started with the steps to fetch stock market data using Python selenium. You can loop the steps for fetching data to get access to live market data right on your Python application.

Step 1. Importing Modules

To start with, we need to import selenium and webdriver (chrome) into our code.

import selenium 
from selenium import webdriver

Step 2. Taking Input

We will take the company’s trading symbol(ticker or stock name) as input and store it in a variable from the user.

company_name = input("Enter the company name: ")

Step 3. Initializing Webdriver

First, we need to download the WebDriver of the web browser which we want to automate.

In my case, I’ve downloaded the same version of chrome WebDriver as Google Chrome. We will also check whether the user has entered a company name or not. If we have a company name then we will initialize the WebDriver.

if(company_name != ''):
    driver = webdriver.Chrome('C://software/chromedriver.exe')

For initializing the webdriver we need to pass the path of our downloaded WebDriver as in our computer system as shown above.

Step 4. Access The Website

Before we start scraping the website, we first need to access the website. We can do this with the help of the get() method. By using string concatenation, we’ve added the value of the company_name variable to the base URL of stock data on the NSE website.

We do this to fetch stock data as per the input symbol. The company_name can be INFY, TCS, ITC, RELIANCE, BRITANNIA, etc., provided it should be a valid stock symbol.

driver.get('https://www.nseindia.com/get-quotes/equity?symbol='+ company_name)

For this tutorial, we’re accessing the webpage with the stock data of Britannia.

Step 5. Find The Specific Elements We Want To Scrape 

Below are the current stock values of Britannia which we want to scrape. So we’ll inspect these values to find its HTML element, using the inspect tool of the browser.

Stock Data of BRITANIA for web scraping
Real-time data of Stock, which we need to scrape

We find the below HTML code from the NSE website for BRITANIA symbol.

<table id="priceInfoTable">                                         
<td>Open</td> 
<td>Close*</td>                                                                
<td>title="Volume Weighted Average Price">VWAP</td>                                                                    
<td>Lower Band</td>                                                                    
<td>Upper Band</td>                                                                    
<td>Price Band</td>                                                                    
<tr><td style="">3,605.15</td>
<td>3,606.00</td>
<td>3,618.30</td>
<td>3,611.97</td>
<td>3,244.65</td>
<td>3,965.65</td>
<td>No Band</td>
</table>

After inspecting we found that all the desired values are in the id named – priceInfoTable. So we’ll access these values by using the get_element_by_id() method. We need to pass the id name priceInfoTable.

britania_stock = driver.find_elements_by_id('priceInfoTable')

Step 6. Store The Scraped Information In a List

When we scrape any data from a webpage, you can’t always make sense of it when working with code. In order to make it usable and readable, we’ll store this data in a list.

britania_list = []
for p in range(len(britania_stock)):
    britania_list.append(britania_stock[p].text)

When we print this list it will return all values as a single element of a list. So we’ll write another for loop and print these values in a new line.

Lastly, we use driver.quit() – which is a method to close all browser windows.

The full working code is below:

from selenium import webdriver
import time

company_name = input("Enter the stock name: ")

if(company_name != ''):

    driver = webdriver.Chrome('C://software/chromedriver.exe')
    driver.get('https://www.nseindia.com/get-quotes/equity?symbol='+ company_name)

    #to let the webpage load completely
    time.sleep(5) 

    britania_stock = driver.find_elements_by_id('priceInfoTable')

    britania_list = []
    for p in range(len(britania_stock)):
        britania_list.append(britania_stock[p].text)

    for i in britania_list:
        print(i,end="\n")

driver.quit()

The output of this code will be:

Input of web scrape of stock market data using python selenium
Output of web scrape of stock market data using python selenium
Output as per the inputted ticker symbol

Conclusion

Go ahead and experiment the same with other websites, and maybe even cryptocurrency websites to grab live prices for your app. Note that scraping for commercial purposes can be against the policies of many websites and you need to ensure that you use this data for personal uses only.

Hope you enjoyed this article. Follow http://askpython.com for more such tutorials!