What is the Page Object Model in Selenium?

The Page Object Model (POM) is a design pattern in Selenium that creates an object repository for web elements. In simple terms, it is a way to structure your test code to make it more readable, maintainable, and reusable.

The main idea behind the Page Object Model is to have a separate class file for each page of the application. Each web page in the application should have a corresponding page class. This page class will identify the web elements of that web page and also contains page methods which perform operations on those web elements.

Advantages of POM

  1. Reusability: We could achieve reusability of the code. The same method can be used by many different test cases.
  2. Code Maintenance: Code is easy to maintain. If UI changes for any page, it don’t require us to change any tests, we just need to change only the code within the page objects.
  3. Readability: Improves readability due to clean separation between test code and page specific code.

Example in Python

Let's take an example of a login page. We will first create a LoginPage class that will identify the web elements and contains page methods.

from selenium import webdriver

class LoginPage:
    def __init__(self):
        self.driver = webdriver.Firefox()

        # Locators
        self.username_textbox_id = "username"
        self.password_textbox_id = "password"
        self.login_button_id = "loginBtn"

    def set_username(self, username):
        self.driver.find_element_by_id(self.username_textbox_id).clear()
        self.driver.find_element_by_id(self.username_textbox_id).send_keys(username)

    def set_password(self, password):
        self.driver.find_element_by_id(self.password_textbox_id).clear()
        self.driver.find_element_by_id(self.password_textbox_id).send_keys(password)

    def click_login(self):
        self.driver.find_element_by_id(self.login_button_id).click()

Then we can use this LoginPage class in our tests like this:

def test_login_valid(self):
    login_page = LoginPage()
    login_page.set_username("valid_user")
    login_page.set_password("valid_password")
    login_page.click_login()

This way, we separate the page-specific code from our tests. If the UI changes in the future, we only need to update the LoginPage class.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon