How do I use Selenium in Python for automatic login? Detailed tutorials

This article walks you through how to use the Selenium library with Chrome drivers to automatically log in to websites and verify successful logins in Python.

How does Python Selenium automatically login? Controlling a web browser from a program is useful in many scenarios, and example use cases are website text automation and web scraping. A very popular framework for this automation is Selenium WebDriver.

How do I use Selenium for automatic login? Selenium WebDriver is a browser control library that supports all major browsers (Firefox, Edge, Chrome, Safari, Opera, etc.) and works with different programming languages, including Python. In this tutorial, we’ll use its Python bindings to automatically log in to the website.

Automating the login process on the website proves to be convenient. For example, you might want to automatically edit your account settings, or you might want to pull some information that requires you to log in, etc.

We have a tutorial on extracting web forms using the BeautifulSoup library, so you may want to combine extracting login forms and populating them with the help of this tutorial.

Introduction to the Python Selenium Autologin Example – First, let’s install Selenium for Python:

The next step is to install the driver specific to the browser we want to control. A download link is available on this page. I’m installing ChromeDriver, but feel free to use what you like best.

To make things concrete, I’m going to use the Github login page to demonstrate how to use Selenium autologin.

How does Python Selenium automatically login? Open a new Python script and initialize WebDriver:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

# Github credentials
username = "username"
password = "password"

# initialize the Chrome driver
driver = webdriver.Chrome("chromedriver")

Once you’ve downloaded and unzipped the driver for your operating system, place it in your current directory or a known path so you can pass it to the class. In my case, chromedriver.exe is in the current directory, so I just pass its name to the constructor.webdriver.Chrome()

How do I use Selenium for automatic login? Since we’re interested in automating Github logins, we’ll navigate to the Github login page and inspect the page to identify its HTML elements:

The login and password input boxes, and the name of the login button will be useful for us to retrieve these code elements and insert them into the programming.id

Python Selenium auto-login example: Note that the username/email address input field has, where the password input field has of, see also the submit button has of, the following code goes to the GitHub login page, extracts these elements, fills in the credentials, and clicks the button:login_field id id password name commit

# head to github login page
driver.get("https://github.com/login")
# find username/email field and send the username itself to the input field
driver.find_element_by_id("login_field").send_keys(username)
# find password input field and insert password as well
driver.find_element_by_id("password").send_keys(password)
# click login button
driver.find_element_by_name("commit").click()

The function retrieves an HTML element through which it simulates a keystroke, and the code cell above will cause Chrome to enter an email and password, and then click the login button.find_element_by_id() id send_keys()

How does Python Selenium automatically login? The next thing to do is to determine if our login is successful. There are many ways to detect this, but in this tutorial, we will do it by detecting the error that appears when logging in (of course, this will go from one website to the other).

How do I use Selenium for automatic login? The image above shows what happens when we insert the wrong credentials, and you’ll see a new HTML element whose class has the text “Incorrect username or password”.div "flash-error"

The following Python Selenium auto-login sample code is responsible for performing a login, waiting for the page to load, and checking for errors:WebDriverWait()

# wait the ready state to be complete
WebDriverWait(driver=driver, timeout=10).until(
    lambda x: x.execute_script("return document.readyState === 'complete'")
)
error_message = "Incorrect username or password."
# get the errors (if there are)
errors = driver.find_elements_by_class_name("flash-error")
# print the errors optionally
# for e in errors:
#     print(e.text)
# if we find that error message within errors, then login is failed
if any(error_message in e.text for e in errors):
    print("[!] Login failed")
else:
    print("[+] Login successful")

We use WebDriverWait to wait for the document to load, which executes Javascript in the context of the browser and returns JS code when the page loads, otherwise.execute_script()return document.readyState === 'complete' True False

Finally, we turn off our drivers:

# close the driver
driver.close()

How does Python Selenium automatically log in? summary

Ok, now you can automatically log in to the website of your choice. Be aware that Github will block you when you run the script multiple times with the wrong credentials, so be aware of that.

Now that you can do what you want after logging in with your account, you can add the code to the line where we print “Login successful”.

Also, if you successfully log in with a real account, you may encounter an email confirmation, and to bypass it, you have to programmatically read your email using Python extract the confirmation code, and then insert it in real-time using Selenium, which is too challenging, isn’t it? Good luck!