Building a Page Object Model (POM) in Python
๐️ Building a Page Object Model (POM) in Python
What is Page Object Model (POM)?
POM is a design pattern in test automation that creates an abstraction layer for web pages. Each page is represented by a class, encapsulating elements and actions, which makes tests easier to read, maintain, and reuse.
Why Use POM?
Improves code readability and maintainability
Centralizes locators and page actions
Facilitates reusability across multiple tests
Reduces code duplication
Step-by-Step Guide to POM in Python
1. Setup
Make sure you have Selenium installed:
bash
Copy
Edit
pip install selenium
2. Create a Page Class
Each web page is represented as a class. It includes:
Locators for page elements
Methods to interact with those elements
Example: Login Page Object
python
Copy
Edit
from selenium.webdriver.common.by import By
class LoginPage:
def __init__(self, driver):
self.driver = driver
# Locators
self.username_input = (By.ID, "username")
self.password_input = (By.ID, "password")
self.login_button = (By.ID, "loginBtn")
# Methods to interact with the page
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()
3. Use the Page Object in Your Test
python
Copy
Edit
from selenium import webdriver
import time
# Initialize the WebDriver (example with Chrome)
driver = webdriver.Chrome()
driver.get("https://example.com/login")
# Create an instance of the LoginPage
login_page = LoginPage(driver)
# Use methods defined in the page object
login_page.enter_username("testuser")
login_page.enter_password("mypassword")
login_page.click_login()
time.sleep(5) # Wait to observe result (avoid in real tests; use explicit waits instead)
driver.quit()
4. Best Practices
Keep locators private inside the page class.
Expose only meaningful actions as public methods.
Avoid putting assertions inside page classes; keep those in test scripts.
Use explicit waits (WebDriverWait) instead of time.sleep() for reliability.
5. Example with Explicit Wait
python
Copy
Edit
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def click_login(self):
WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(self.login_button)
).click()
✅ Summary
POM organizes test automation code by page.
Page classes hold locators and interaction methods.
Tests use page objects for clear, maintainable code.
Learn Selenium Python Training in Hyderabad
Read More
Selenium with Pytest: Writing and Running Tests
Creating a Data-Driven Framework with Selenium and Python
Using unittest Framework with Selenium in Python
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment