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/chromedriver_linux64.zip -d /usr/local/bin $ chromedriver --version ChromeDriver 103.0.5060.53
Create a login.py
file with the contents as follows:
# login.py # by www.ShellHacks.com from selenium import webdriver from selenium.webdriver.common.by import By from random import randint from time import sleep driver = webdriver.Chrome("/usr/local/bin/chromedriver") # Time to wait for element's presence driver.implicitly_wait(10) driver.get('https://www.instagram.com/') # Sleep a random number of seconds (between 5 and 10) sleep(randint(5,10)) # Click 'Accept cookies' button on www.instagram.com accept_cookis_button = driver.find_element(By.XPATH, '//button[text()="Only allow essential cookies"]') accept_cookis_button.click() sleep(randint(5,10)) username_input = driver.find_element(By.CSS_SELECTOR, 'input[name="username"]') password_input = driver.find_element(By.CSS_SELECTOR, 'input[name="password"]') username_input.send_keys("yourUsername") password_input.send_keys("yourP@ssw0rd") sleep(randint(5,10)) login_button = driver.find_element(By.XPATH, '//button[@type="submit"]') login_button.click() # Close the browser after 100 seconds sleep(100) driver.close()
Execute the login.py
to login to Instagram:
$ python login.py
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 →