Page Object Model and Page Factory in Selenium Python

Related Product On This Page What is Page Object Model (POM) in Selenium?

February 19, 2026 · 7 min read · Tool Comparison
Related Product

Page Object Model and Page Factory in Selenium Python

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

Overview

The Page Objection Model is a pattern pattern use in Selenium mechanisation essay to make an object repository for web elements. It heighten test maintenance, legibility, and reusability by separating UI element locators from trial scripts.

How Page Object Model Works

Here & # 8217; s how the POM works:

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

Benefits of Page Object Model (POM)

Some of the primary welfare of POM include:

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

This article explore the implementation of the Page Object Model in Selenium expend Python, enabling efficient cross-browser testing for your site.

What is Page Object Model (POM) in Selenium?

The Page Object Model (POM) is a structured approach to compose Selenium automation tests. Instead of writing locators and actions directly in exam cases, POM stores them in dedicated page classes. This makes automation hand cleaner, easier to hold, and more reusable. If the application ’ s UI changes, update are need 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 amend the quality of your testing operation to ameliorate the readability and dependableness of the scripts.
  • Site Maintenance: It is easier to preserve the site over time. Suppose if something got changed on any page, you could easily detect the functions and locators that demand 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 squad.
  • Overall Productivity: The POM can make it easygoing for new team members to get up to speed and boost overall team productivity.
  • Reusing Code: Using POM, you can reuse your role 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 puppet for any organization. By make one, you can help improve the calibre 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 initialize web elements at runtime and cater extra features for better examination efficiency.

To endorse the Page Object pattern, Page Factory in Python uses a dictionary to announce all web component, where dictionary key act as WebElement or class member variables with lengthy WebElement methods.

Unlike the standard POM, Page Factory initializes all web constituent at once when the page family is instantiated. Additionally, it heighten, such as pass the click () method to include an explicit wait until the ingredient is clickable, amend exam stability.

Page Object Model in Selenium with Python using Selenium page manufactory

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

pip install selenium-page-factory

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

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

Extended WebElements Methods in selenium-page-factory

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

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 & amp; Page Factory in Selenium Python

A well-structured labor keeps test scripts organized and leisurely to maintain. Below is a distinctive folder construction for implementing Page Object Model (POM) with Page Factory in Selenium habituate Python.

Pre-requisites:

  • IDE& # 8211; PyCharm
  • Python& # 8211; 3.4 or higher
  • Framework Used& # 8211; Pytest
  • Package Used& # 8211; Selenium, selenium-page-factory, pytest

To install bundle you can use pip.

pip install selenium-page-factory

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 exam software.

Project Structure:

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

Page Class

Code Snippet:

from seleniumpagefactory.Pagefactory import PageFactory form SignInPage (PageFactory): def __init__ (self, driver): self.driver = driver locators = {'user_name ': ('CSS ', `` # username stimulus ''), '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 ()

The chase is the Page Class for the Sign In Page. The PageFactory category is imported from its faculty, and a new class named SignInPage is created, inherit from PageFactory. Each page class must initialize the driver within the __init__ method. Locators are store in a lexicon, where the key represents the locator name, and the value is a tuple containing the locator character and its match value.

locator = {'user_name ': ('CSS ', `` # username input ''), 'password ': ('CSS ', ' # password stimulation '), 'login_btn ': ('ID ', 'login-btn ')}

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

self.locator_name.function ()

All page classes follow the same structure. Below is an example of a page family 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 () affirm retrieved_username == `` demouser ''

Test Case

Here is the codification snippet for test_browserstack.py

from selenium import webdriver from src.pages.homepage importation Homepage from src.pages.sign_in_page importee 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 ()

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

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

This approach allows test cases to be action utilise the Page Object Model, assure that the method inside page classes can be reused across multiple examination cases.

Since the pytest model is utilise, the test case can be executed by running a pytest command.

pytest -v

Here is the picture of our test run.

Run Tests on Multiple Browsers & amp; Real Devices with BrowserStack

BrowserStack gives you crying access to of 3500+ real devices and background browsers. Running your Selenium test with Python on BrowserStack is simple yet effectual, perpetually.

We involve 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 ', # examination 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)

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

Talk to an Expert

Conclusion

Page Object Model is a outstanding way to organize your codification and do it more reusable and understandable. It helps a lot when you need to do maintenance with your test handwriting. In Automation Testing, our code often interrupt due to changes in selector which need to be fixed many times in the code. Page Factory assist debug that alteration and organize code in such a way that we can easy vary our selectors.

Run your on multiple browsers using BrowserStack Automate as it & # 8217; s difficult to test your Web App on multiple browsers with their different variant topically. But, BrowserStack supply you with 3500+ real devices and web browsers to try your coating using Selenium. You can also test that in parallel to

Pro Tip:Want to dive deeper into BrowserStack mechanization with gratuitous interactional courses and exercises?

Tags
75,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free