Skip to main content

Starting with Selenium Web-Driver using Python by example

Selenium Web-Driver is an open source tool which is used to automate web-applications. It uses drivers to support different web-browsers. Selenium supports different language bindings for doing automation. In this post, I'll be using Python binding as an example.

Our automation task for this post is as follows :-
  • Open this website 
  • Select the Login Page using login option from drop-down menu
  • Enter user-name and password (fake credentials)
  • Look for error message and compare it with the expected message
  • Take a screenshot of the website for reference
Before, we get into the example code, let's do the setup required for running Selenium.
  • Install Selenium using pip (pip install selenium)
  • Install the drivers for the web-browser of your choice. I am using Chrome Webdriver for my example. Visit this website and follow the links to install web-browser driver.
In order to execute the following code, you need to run the "chromedriver" on a seperate terminal and then run the Python code. Let's understand the code flow in the next section.


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

CHROMEDRIVER = "/Users/sarbjit/selenium/webdrivers/chromedriver"
WEBSITE = "https://sarbjit87.pythonanywhere.com/borrowbooks/default/index"

class BorrowBooksWebsite(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome(executable_path=CHROMEDRIVER)

    def test_login_page(self):
        """Visit the login page of the website"""
        self.driver.get(WEBSITE)

        # Select the Login button from the drop-down in the website (Top-Right)
        elem = self.driver.find_element_by_css_selector(".dropdown-toggle")
        elem.click()

        elem = self.driver.find_element_by_css_selector("ul.dropdown-menu li:last-child a")
        elem.click()

        # Find the User Email and Password input fields and provide some fake credentials

        elem = self.driver.find_element_by_css_selector("#auth_user_email")
        elem.clear()
        elem.send_keys("[email protected]")
        elem = self.driver.find_element_by_css_selector("#auth_user_password")
        elem.clear()
        elem.send_keys("test")
        elem.send_keys(Keys.RETURN)

        # Look for "Invalid login" error message 
        elem = self.driver.find_element_by_css_selector('div[class1*="w2p_flash"]')
        self.assertEquals(elem.text, "Invalid login")

    def tearDown(self):
        time.sleep(5) # Wait for 5 seconds to see the website results and close
        # Save a screenshot of the web-page by finding 'body' tag
        element = self.driver.find_element_by_tag_name('body')
        element_png = element.screenshot_as_png
        with open("snapshot.png", "wb") as file:
            file.write(element_png)
        self.driver.close()

if __name__ == '__main__':
    unittest.main(verbosity=2)

First few lines are importing the packages requireed for creating an automated test case using Python and Selenium. In this example, I am using Python UnitTest module for creating test case.

In the setUp, we are creating an instance of webdriver by providing the path to the Chrome Driver location.

In the test_login_page, we are using the get method on driver instance to load the website. Next, we will use CSS Selectors to locate an element in the loaded page. Selenium Webdriver supports different methods to locate the elements including using CSS Selectors, XPath queries. You can refer to my posts regarding CSS Selectors and XPath queries for reference.

We are using find_element_by_css_selector method on the driver instance to locate the Login dropdown and then using the click method on the returned Web Driver Instance. We require two clicks here, one to click on drop-down and second to click on Login link in the drop-down.

Once we load the Login page, we find the Input Text Element for User-Name and Password using CSS Selectors. Now, we are using another method clear() - to clear any existing text in the input text field and then using the send_keys() method to provide the username and password. Note, we are using keys.RETURN which is used to send enter key.

For verification of error message, we are again using css selector to find the text message and comparing it with expected message. 

In the tearDown method, we are taking a screen-shot of the web-page by locating body tag and exiting Chrome.


Comments