Python: Login to Website – Selenium

Selenium is an open source tool that automates web browsers and is widely used for automated testing of web applications.

With Python and Selenium you can easily create a script that automates login to a website, that is very useful, for example, for web scraping.

This note shows how to create a Python script to login to a website automatically using Selenium on the example of Instagram.

Cool Tip: How to download a file from URL using Python! Read More →

Login to a Website using Selenium in Python

Create a project’s working directory:

$ mkdir -p ~/projects/login2website

Inside the project’s working directory create and activate a virtual environment:

$ cd ~/projects/login2website
$ python3 -m venv venv
$ . venv/bin/activate

Install Selenium:

$ pip install selenium
$ pip show selenium | grep -i version
Version: 4.3.0

Download and unzip the latest stable version of a ChromeDriver (the executable that Selenium uses to interact with Chrome):

$ sudo unzip ~/Downloads/ -d /usr/local/bin
$ chromedriver --version
ChromeDriver 103.0.5060.53

Create a file with the contents as follows:

# by

from selenium import webdriver
from import By
from random import randint
from time import sleep

driver = webdriver.Chrome("/usr/local/bin/chromedriver")
# Time to wait for element's presence

# Sleep a random number of seconds (between 5 and 10)

# Click 'Accept cookies' button on
accept_cookis_button = driver.find_element(By.XPATH, '//button[text()="Only allow essential cookies"]')


username_input = driver.find_element(By.CSS_SELECTOR, 'input[name="username"]')
password_input = driver.find_element(By.CSS_SELECTOR, 'input[name="password"]')


login_button = driver.find_element(By.XPATH, '//button[@type="submit"]')

# Close the browser after 100 seconds

Execute the to login to Instagram:

$ python

Cool Tip: How to add random delays in Python to not get banned! Read More →

Finding an XPath and CSS Selector

In the example above i use the XPath (XML path) and CSS Selectors to identify the web elements that are required to automate the login process.

To get an XPath string or a CSS Selector string of an element, right-click on it in your web browser, select “Inspect”, right-click on the highlighted area and go to “Copy” → “Copy XPath” or “Copy selector”:

This will copy the XPath or the CSS Selector of the highlighted item to your clipboard.

Alternatively you can use a SelectorsHub plugin:

Cool Tip: How to set the ‘User-Agent’ HTTP request header in Python! Read More →

Leave a Reply