Why Use Page Object Model in Selenium: Benefits and Example
Page Object Model in Selenium helps organize web page elements and actions into separate classes, making tests easier to read and maintain. It reduces code duplication and improves test reliability by keeping locators and methods in one place.How It Works
The Page Object Model (POM) works like a map for your test scripts. Imagine you have a website with many pages, each with buttons, fields, and links. Instead of writing code to find and click these elements everywhere, you create a separate class for each page. This class holds all the details about the page elements and the actions you can do on them.
Think of it like a remote control for a TV. The remote has buttons labeled for each function, so you don’t have to open the TV and press the buttons inside. Similarly, the POM class acts as a remote control for the web page, letting your test scripts use simple commands without worrying about the details.
This separation makes your tests cleaner and easier to update. If the page changes, you only update the page class, not every test that uses it.
Example
This example shows a simple Page Object Model class for a login page and a test that uses it.
from selenium import webdriver from selenium.webdriver.common.by import By class LoginPage: def __init__(self, driver): self.driver = driver self.username_input = (By.ID, "username") self.password_input = (By.ID, "password") self.login_button = (By.ID, "loginBtn") def enter_username(self, username): self.driver.find_element(*self.username_input).send_keys(username) def enter_password(self, password): self.driver.find_element(*self.password_input).send_keys(password) def click_login(self): self.driver.find_element(*self.login_button).click() # Test using the Page Object Model driver = webdriver.Chrome() driver.get("https://example.com/login") login_page = LoginPage(driver) login_page.enter_username("testuser") login_page.enter_password("securepass") login_page.click_login() print("Login test executed") driver.quit()
When to Use
Use the Page Object Model when your test suite grows beyond a few simple tests. It is especially helpful when:
- You have many tests interacting with the same pages.
- The web pages change often, requiring updates to locators or actions.
- You want to keep your test code clean and easy to understand.
- You work in a team where multiple people write or maintain tests.
For example, in a large e-commerce site, you might have separate page objects for the home page, product page, cart, and checkout. This keeps your tests organized and reduces errors.
Key Points
- Page Object Model separates page details from test logic.
- It improves test readability and maintenance.
- Reduces code duplication by reusing page methods.
- Makes updating tests easier when UI changes.
- Supports teamwork by providing a clear structure.