Page Object Model and Page Factory in Selenium Python

Know about Page Object Model & Page Factory in Selenium Python for better object repository structuring

Get Started free
Page-Object-Model-and-Page-Factory-in-Selenium-Python
Home Guide Page Object Model and Page Factory in Selenium Python

Page Object Model and Page Factory in Selenium Python

Maintaining automation test scripts can become challenging as applications grow. The Page Object Model (POM) simplifies this by organizing web elements and actions into reusable page classes, making tests more readable and easier to maintain.

Overview

The Page Objection Model is a design pattern used in Selenium automation testing to create an object repository for web elements. It enhances test maintenance, readability, and reusability by separating UI element locators from test scripts.

How Page Object Model Works

Here’s how the POM works:

  • Encapsulation of Web Elements: Defines web elements in separate classes to keep test scripts clean.
  • Code Reusability: Commonly used web actions are stored in methods within page classes.
  • Test Script Simplicity: Test cases interact with methods instead of directly using locators.
  • Maintenance Efficiency: Changes in UI only require updates in one place rather than multiple test scripts.
  • Separation of Concerns: UI elements (Page classes) are separate from test logic (Test scripts).

Benefits of Page Object Model (POM)

Some of the primary benefits of POM include:

  • Enhances code reusability
  • Boosts test readability
  • Improves team collaboration
  • Simplifies site maintenance
  • Increases overall productivity

This article explores the implementation of the Page Object Model in Selenium using Python, enabling efficient cross-browser testing for your website.

What is Page Object Model (POM) in Selenium?

The Page Object Model (POM) is a structured approach to writing Selenium automation tests. Instead of writing locators and actions directly in test cases, POM stores them in dedicated page classes. This makes automation scripts cleaner, easier to maintain, and more reusable. If the application’s UI changes, updates are needed only in the page class, not in every test script.

There are many benefits to creating a POM, such as:

  • Testing Quality: The POM helps you write tests that are easy to understand and maintain. This can help improve the quality of your testing process to improve the readability and reliability of the scripts.
  • Site Maintenance: It is easier to maintain the site over time. Suppose if something got changed on any page, you could easily find the functions and locators that need to be changed by that page class.
  • Team Collaboration: The POM can help with collaboration between team members and significantly improve the efficiency of your team.
  • Overall Productivity: The POM can make it easier for new team members to get up to speed and boost overall team productivity.
  • Reusing Code: Using POM, you can reuse your functions in different Test Scripts by importing them from Page Class. It doesn’t require writing the same functions in different test cases.

With all of these benefits, it is clear that a POM can be a valuable tool for any organization. By creating one, you can help improve the quality of your software testing process and team collaboration.

What is Page Factory?

Page Factory is a method of implementing the Page Object Model (POM) in Selenium. It enhances POM by initializing web elements at runtime and providing additional features for better test efficiency.

To support the Page Object pattern, Page Factory in Python uses a dictionary to declare all web elements, where dictionary keys act as WebElement or class member variables with extended WebElement methods.

Unlike the standard POM, Page Factory initializes all web elements at once when the page class is instantiated. Additionally, it enhances WebElement methods, such as extending the click() method to include an explicit wait until the element is clickable, improving test stability.

Page Object Model in Selenium with Python using Selenium page factory

It is easy implement page factory in Selenium with Python by using the selenium-page-factory package. Install it by using

pip install selenium-page-factory
Copied

To use selenium-page-factory every Page in the Page Object Model should have a WebDriver object as a class member as shown below:

class PageClass(PageFactory):

def __init__(self, driver):
self.driver = driver
Copied

BrowserStack Automate Banner 8

Extended WebElements Methods in selenium-page-factory

set_textget_text
clear_textclick_button
double_clickget_list_item_count
select_element_by_textselect_element_by_index
select_element_by_valueget_all_list_item
get_list_selected_itemhighlight
is_Enabledis_Checked
getAttributehover
visibility_of_element_locatedinvisibility_of_element_located
element_to_be_clickableexecute_script
context_clicktext_to_be_present_in_element
click_and_hold

Sample Project Structure for Page Object Model & Page Factory in Selenium Python

A well-structured project keeps test scripts organized and easy to maintain. Below is a typical folder structure for implementing Page Object Model (POM) with Page Factory in Selenium using Python.

Pre-requisites:

  • IDE – PyCharm
  • Python – 3.4 or higher
  • Framework Used – Pytest
  • Package Used – Selenium, selenium-page-factory, pytest

To install packages you can use pip.

pip install selenium-page-factory
Copied

Setup:

  •  Create a Python project in Pycharm.
  •  Add 2 Python Package src and test.
  •  Add Page Classes under src.pages package.
  •  Add test scripts under test package.

Project Structure:

Project Structure

POM structure has a structure for all the pages. This package consists of class files related to every pages. Each page class contains methods specific to the actions that can be performed on that page.

Page Class

Page Class

Code Snippet:

from seleniumpagefactory.Pagefactory import PageFactory

class SignInPage(PageFactory):
def __init__(self, driver):
self.driver = driver

locators = {
'user_name': ('CSS', "#username input"),
'password': ('CSS', '#password input'),
'login_btn': ('ID', 'login-btn')
}

def select_username(self):
self.user_name.set_text('demouser\n')

def select_password(self):
self.password.set_text('testingisfun99\n')

def click_login(self):
self.login_btn.click()
Copied

The following is the Page Class for the Sign In Page. The PageFactory class is imported from its module, and a new class named SignInPage is created, inheriting from PageFactory. Each page class must initialize the driver within the __init__ method. Locators are stored in a dictionary, where the key represents the locator name, and the value is a tuple containing the locator type and its corresponding value.

locators = {
'user_name': ('CSS', "#username input"),
'password': ('CSS', '#password input'),
'login_btn': ('ID', 'login-btn')
}
Copied

Next, all the necessary functions for interacting with the page are defined, such as entering the username and password. The syntax for writing these functions is as follows:

self.locator_name.function()
Copied

All page classes follow the same structure. Below is an example of a page class for the Home Page.

page class for the home page

Code Snippet:

from seleniumpagefactory.Pagefactory import PageFactory

class Homepage(PageFactory):
def __init__(self, driver):
self.driver = driver

locators = {
"sign_in": ("ID", "signin"),
"user_name": ("CSS", ".username")
}

def click_sign_in(self):
self.sign_in.click()

def get_username(self):
retrieved_username = self.user_name.get_text()
assert retrieved_username == "demouser"
Copied

Test Case

test case - BrowserStack

Here is the code snippet for test_browserstack.py

from selenium import webdriver
from src.pages.homepage import Homepage
from src.pages.sign_in_page import SignInPage

def test_browserstack():
driver = webdriver.Chrome()
driver.get("https://bstackdemo.com/")

homepage = Homepage(driver)
sign_in_page = SignInPage(driver)

homepage.click_sign_in()

sign_in_page.select_username()
sign_in_page.select_password()
sign_in_page.click_login()
homepage.get_username()
driver.quit()
Copied

In this test case, all the methods defined within the page classes are utilized.

  1. First, we need to import those page classes.
  2. Create a function for your test case.
  3. Initialize the driver for the chrome web driver.
  4. Make objects for the page classes.
  5. Call functions using the objects.

This approach allows test cases to be executed using the Page Object Model, ensuring that the methods inside page classes can be reused across multiple test cases.

Since the pytest framework is used, the test case can be executed by running a pytest command.

pytest -v
Copied

Here is the video of our test run.

Run Tests on Multiple Browsers & Real Devices with BrowserStack

BrowserStack gives you instant access to Selenium Grid of 3500+ real devices and desktop browsers. Running your Selenium tests with Python on BrowserStack is simple yet effective, always.

Run Selenium Tests for Free

We need to replace browser = webdriver.Chrome() to

desired_cap = {
'os_version': '11',
'resolution': '1920x1080',
'browser': 'Chrome',
'browser_version': 'latest',
'os': 'Windows',
'name': 'BStack-[Python] Sample Test', # test name
'build': 'BStack Build Number 1' # CI/CD job or build name
}
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub', desired_capabilities=desired_cap)
Copied

It will start running your test cases on the BrowserStack cloud.

Talk to an Expert

Conclusion

Page Object Model is a great way to organize your code and make it more reusable and understandable. It helps a lot when you need to do maintenance with your test scripts. In Automation Testing, our code often breaks due to changes in selectors which need to be fixed many times in the code. Page Factory helps debug that change and organize code in such a way that we can easily change our selectors.

Run your test cases in parallel on multiple browsers using BrowserStack Automate as it’s difficult to test your Web App on multiple browsers with their different versions locally. But, BrowserStack provides you with 3500+ real devices and web browsers to test your application using Selenium. You can also test that in parallel to accelerate CI/CD pipelines.

Pro Tip: Want to dive deeper into BrowserStack automation with free interactive courses and exercises? Visit Test University

Tags
Automation Testing Selenium Selenium Webdriver