Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Sunday, November 22, 2020

Automatic Login to Zerodha using Python and Selenium

Hello Readers,

 

Today we will try to learn browser automation using Python and Selenium automation tool.

 

We will write a code to automate login process of Zerodha trading platform using selenium and python in Google Chrome browser.

Place a file named zerodha-credentials.json at the same location as the actual python script with zerodha credentials as below:

{
"username": "ab12312",
"password": "changeit",
"pin": "123123"
}


Run the below script to automatically login, code is mostly self-explanatory leave a comment if any doubt, I will try to respond.

 

from selenium import webdriver
# used to ID the different keys on the keyboard define options
from selenium.webdriver.chrome.options import Options
# locate
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import time
import json
def load_credentials():
with open("zerodha-credentials.json") as creds:
data = json.load(creds)
return data
def get_access_token():
options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(options=options)
# the website we want to open
driver.get("https://kite.zerodha.com")
data = load_credentials()
# identify login section
WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '//div[@class="login-form"]//form')))
# enter the ID
driver.find_element_by_xpath("//*[@type='text']").send_keys(data['username'])
# enter the password
driver.find_element_by_xpath("//*[@type='password']").send_keys(data['password'])
# submit
driver.find_element_by_xpath("//*[@type='submit']").click()
driver.maximize_window()
# sleep for a second so that the page can submit and proceed to upcoming question (2fa)
time.sleep(1)
# identify login section for 2fa
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//div[@class="login-form"]//form')))
# enter the 2fa code
driver.find_element_by_xpath("//*[@type='password']").send_keys(data['pin'])
# submit
driver.find_element_by_xpath("//*[@type='submit']").click()
print(driver.current_url)
# Click on Postions Page
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Positions']"))).click()
# wait for redirection
WebDriverWait(driver, 10).until(EC.url_contains('status=success'))
if __name__ == "__main__":
get_access_token()

Note: Think before storing your credentials in plain text, potential risk of it being compromised. This post is for education purpose to learn how we can automate web surfing using Python.