Automating Zerodha Login with Python, Selenium, and TOTP.
This Python script automates the login process to Zerodha’s Kite Connect API using Selenium and TOTP-based two-factor authentication. It begins by setting the working directory and reading API credentials from a file, then initializes the Kite Connect session and opens the Zerodha login page in a Chrome browser. Using Selenium, it inputs the user ID and password, generates a time-based OTP using a secret key, and submits the login form. After successfully logging in and being redirected, the script extracts the request token from the URL, uses it along with the API secret to generate an access token, and saves this token to a file for future API interactions.
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from kiteconnect import KiteConnect
from selenium.webdriver.common.by import By
from urllib.parse import urlparse, parse_qs
from selenium import webdriver
import time
import os
import pyotp
cwd=os.chdir("D:\GenAi\python\python basic\Strategy")
token_path="api_key.txt"
key_secret=open(token_path,'r').read().split()
kite=KiteConnect(api_key=key_secret[0])
url=kite.login_url()
print(url)
driver = webdriver.Chrome()
driver.get("https://kite.zerodha.com/connect/login?api_key=xxxxxxxxxxxxxx")
time.sleep(3)
userId_field = driver.find_element(By.ID, 'userid')
password_field = driver.find_element(By.ID, 'password')
userId_field.send_keys("xxxxxxxx")
password_field.send_keys("xxxxxxxxxx")
time.sleep(3)
# Click Login
driver.find_element(By.XPATH, "//button[@type='submit']").click()
time.sleep(2)
totp_secret = 'wwqweqweqweqweqweqweqweqweqweq'
totp = pyotp.TOTP(totp_secret)
app_code = totp.now()
print("Your Zerodha App Code:", app_code)
appcode_field = driver.find_element(By.ID, 'userid')
appcode_field.send_keys(app_code)
try:
continue_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Continue')]"))
)
continue_button.click()
print("Clicked the Continue button.")
except Exception as e:
print("Error:", e)
# Replace with your actual TOTP secret key from Zerodha
WebDriverWait(driver, 10).until(lambda d: d.current_url != "https://kite.zerodha.com/connect/login?api_key=xxxxxxxxxxxxxx"
# Get the redirected URL
redirected_url = driver.current_url
print("Redirected to:", redirected_url)
parsed_url = urlparse(redirected_url)
query_params = parse_qs(parsed_url.query)
request_token = query_params.get("request_token", [None])[0]
data=kite.generate_session(request_token,api_secret=key_secret[1])
with open('access_token.txt','w') as file:
file.write(data["access_token"])
Explanation of Above code :
Setup and API Key Loading
cwd = os.chdir("D:\GenAi\python\python basic\Strategy")
- Changes the current working directory to the specified path. This is where your
api_key.txtfile is located.
token_path = "api_key.txt"
- Specifies the filename that contains your API key and secret.
key_secret = open(token_path, 'r').read().split()
- Opens the file, reads its contents, and splits it into a list. Assumes the file contains two space-separated values:
[api_key, api_secret].
Kite Connect Initialization
kite = KiteConnect(api_key=key_secret[0])
- Initializes the Kite Connect object using the API key, Generates the login URL required to authenticate the user.
url = kite.login_url()
Browser Automation with Selenium
- Launches a new Chrome browser window using Selenium WebDriver.
driver = webdriver.Chrome()
driver.get("https://kite.zerodha.com/connect/login?api_key=xxxxxxxxxxxx")
- Navigates to the Zerodha login page using the provided API key.
time.sleep(3)
- Waits for 3 seconds to allow the page to load.
User Credentials Input
userId_field = driver.find_element(By.ID, 'userid')
password_field = driver.find_element(By.ID, 'password')
- Locates the input fields for user ID and password.
userId_field.send_keys("xxxxxxx")
password_field.send_keys("xxxxxxxxx")
- Enters the Zerodha user ID and password into the respective fields.
time.sleep(3)
driver.find_element(By.XPATH, "//button[@type='submit']").click()
- Waits and clicks the login button.
TOTP (Two-Factor Authentication)
time.sleep(2)
totp_secret = 'WEWWRWERWERWQSFDFDSF234324234234'
totp = pyotp.TOTP(totp_secret)
app_code = totp.now()
print("Your Zerodha App Code:", app_code)
- Uses the
pyotplibrary to generate a time-based one-time password (TOTP) using the secret key.
appcode_field = driver.find_element(By.ID, 'userid')
appcode_field.send_keys(app_code)
- Enters the TOTP into the same field (likely a mistake—it should probably be a different field like
'pin'or'totp').
Continue Button and Redirect Handling
try:
continue_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Continue')]"))
)
continue_button.click()
print("Clicked the Continue button.")
except Exception as e:
print("Error:", e)
- Waits for the “Continue” button to be clickable and clicks it. If it fails, prints the error.
Extracting Request Token
WebDriverWait(driver, 10).until(lambda d: d.current_url != "https://kite.zerodha.com/connect/login?api_key=xxxxxxxxxxx")
redirected_url = driver.current_url
print("Redirected to:", redirected_url)
- Waits until the browser is redirected to a new URL after login.
parsed_url = urlparse(redirected_url)
query_params = parse_qs(parsed_url.query)
request_token = query_params.get("request_token", [None])[0]
- Parses the redirected URL to extract the
request_tokenparameter.
Generating Access Token
data = kite.generate_session(request_token, api_secret=key_secret[1])
- Uses the request token and API secret to generate a session and retrieve the access token.
with open('access_token.txt', 'w') as file:
file.write(data["access_token"])
- Saves the access token to a file for future use.
One Comment
binance
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.com/zh-TC/register?ref=DCKLL1YD