How to Automate Login using Selenium in Python

09/11/2021

Contents

In this article, you will learn how to automate login using Selenium in Python.

Automate Login using Selenium in Python

To automate login using Selenium in Python, you can follow these steps:

Install Selenium package:

First, you need to install the Selenium package in Python using pip. You can do this by running the following command in your terminal or command prompt:

pip install selenium
Import the necessary libraries:

You need to import the necessary libraries, which are webdriver from selenium.webdriver, Keys from selenium.webdriver.common.keys, and time.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
Launch the browser:

You need to launch a web browser using the webdriver method, which will open the web browser. In this example, we will use Google Chrome as our web browser.

browser = webdriver.Chrome()
Navigate to the website:

Use the get method to navigate to the website where you want to login.

browser.get("https://example.com/login")
Locate the username and password fields:

Find the username and password fields using the find_element_by_name method.

username = browser.find_element_by_name("username")
password = browser.find_element_by_name("password")
Enter the username and password:

Enter your username and password using the send_keys method.

username.send_keys("your_username")
password.send_keys("your_password")
Submit the login form:

Use the submit method to submit the login form.

password.submit()
Close the browser:

Close the browser using the quit method.

browser.quit()

Here’s the full code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

browser = webdriver.Chrome()
browser.get("https://example.com/login")

username = browser.find_element_by_name("username")
password = browser.find_element_by_name("password")

username.send_keys("your_username")
password.send_keys("your_password")

password.submit()

time.sleep(5)
browser.quit()

Note that you may need to modify the code to match the HTML structure of the website you want to login to.