Implement Browser Automation using Selenium with Python

Selenium is a powerful tool used for testing web pages. Selenium is an API that can support any browser on any os and its script can be written in various programming languages.

In this problem we will use various interfaces and methods by Selenium for example we will be using Webdriver interface defined in selenium webdriver API, Locator expressions which locates the unique HTML element on a web page and Finder methods such as findElement, etc. These are the libraries that we will use to automate our Browser.

Browser Automation using Selenium

So, let’s start…

Install Selenium in the jupyter notebook first.

!pip install Selenium

The first step for any uses is to create an instance of the Webdriver interface. So, we will instantiate the Webdriver first and assign it to a variable browser.

And the second step is to get the URL of the web page using get() method. See the Python code below:

from selenium import webdriver
import time

browser = webdriver.Chrome(r'C:\Users\aman\Downloads\chromedriver.exe')  ### path of chrome driver should be passed as argument
browser.get('https://www.twitter.com') 
time.sleep(2)

The above code will open the browser for us.

Then next thing to do is go to the web page right click login button – select inspect – left-click the three dots on the top left of the highlighted HTML scripts – and click copy xpath.

After we get the locator expression we pass it as an argument to the finder method.

login = browser.find_elements_by_xpath(r'//*[@id="react-root"]/div/div/div/main/div/div/div/div[1]/div/a[2]/div')

This will locate the login button and with click method, it performs same as operation as a mouse click.

login[0].click() 
  
print("Loggin in Twitter")

After successfully loading the login page. We have to pass the user name or id. So, we get the xpath to input the username the same as we did before.

user = browser.find_elements_by_xpath(r'//*[@id="react-root"]/div/div/div[2]/main/div/div/form/div/div[1]/label/div/div[2]/div/input') 

user[0].send_keys('Username')

This will give the input to the username or id.
However, we also need to fill the password. So, again we will get the xpath pf password section.

passwordElement = browser.find_elements_by_xpath(r'//*[@id="react-root"]/div/div/div[2]/main/div/div/form/div/div[2]/label/div/div[2]/div/input')
with open('PW.txt', 'r') as myfile:   
    Password = myfile.read().replace('\n', '')
passwordElement[0].send_keys(Password)

After successfully getting the password its time to log in to the user home page by clicking the submit button.

LOG = browser.find_elements_by_xpath('//*[@id="react-root"]/div/div/div[2]/main/div/div/form/div/div[3]/div/div') 
LOG[0].click() 
print("Login Sucessfull") 
time.sleep(5)

Hence we have successfully implemented browser automation using Selenium.

 

Leave a Reply

Your email address will not be published. Required fields are marked *