Page Object Model and Page Factory in Selenium with Python

December 19, 2024
10 mins
Share this post

In test automation, efficiency, maintainability, and reusability of test scripts are crucial for long-term success. Page Object Model (POM) and Page Factory are two essential design patterns in Selenium with Python that help achieve these goals. 

With POM, each web page is represented as a class, and the interactions with page elements are defined as methods, promoting the "separation of concerns" principle. 

On the other hand, Page Factory acts as a lightweight implementation of POM, offering a more efficient way to initialize web elements.

This blog delves into the concepts, benefits, and differences between Page Object Model (POM) and Page Factory in Selenium. We’ll provide a step-by-step guide on implementing POM, setting up Page Factory, and using them in test automation frameworks. 

By the end of this blog, you’ll understand when to use POM, how it improves test automation and the key differences that distinguish POM from Page Factory. 

Constantly Facing Software Glitches and Unexpected Downtime?

Discover seamless functionality with our specialized testing services.

Why you should keep scrolling:

🚀To understand what Page Object Model (POM) and Page Factory are and how they work in Selenium with Python.

🚀 To learn how to set up and implement these design patterns in your automation framework.

🚀 To explore the critical differences between POM and Page Factory and when to use each approach.

🚀To discover the key benefits, including improved maintainability, readability, and reduced code duplication.

What is a Page Object Model (POM)??

The Page Object Model (POM) is a design pattern widely used in Selenium test automation to create maintainable, reusable, and scalable test scripts. In POM, each web page of the application is represented as a separate class

This class contains web elements (like buttons, text boxes, and links) and corresponding methods that interact with them, making it easier to perform user actions on the page. 

By following this structure, test scripts become more readable and maintainable as the logic to locate elements is separated from the actual test logic. 

This separation of concerns ensures that even if the user interface changes, only the Page Object needs to be updated, not the test scripts.

The Selenium Page Object Model helps in reducing code duplication, enhancing readability, and making the framework more maintainable. Instead of directly referencing locators in the test scripts, POM allows testers to use the Page Object Model design pattern, where locators are defined as class variables. This makes it easy to handle changes in the UI structure. To better understand, consider a Page Object Model example for a login page. 

The login page class will have locators for the username, password, and login button along with methods like enter_username(), enter_password(), and click_login(). This modular approach is a key reason why the Page Object Model in Selenium is widely used for building robust test automation frameworks.

Why Use Page Object Model (POM) ??

The Page Object Model (POM) is used in Selenium to create more maintainable, scalable, and readable test automation frameworks. POM provides a structured approach where each page of the application is represented as a separate class with web element locators and page-specific methods.

This approach allows for better separation of concerns, making it easier to maintain and update test scripts when there are changes in the user interface. This design pattern improves the modularity and reusability of code, as the same page elements and actions can be used across multiple test cases.

Another reason to use POM in Selenium is to reduce code duplication and promote code reusability. By storing element locators in a single location (Page Class), you can avoid hardcoding locators in every test script. 

Understanding the Concept of Page Factory

Page Factory is an enhancement of the Page Object Model (POM) used in Selenium to create a more efficient and faster way to initialize web elements. It provides a mechanism to initialize web elements using @FindBy annotations, making it easier to locate elements on a page. Instead of declaring locators manually, Page Factory in Selenium initializes them automatically when the Page Object class is instantiated. 

The key difference between Page Factory and Page Object Model is that Page Factory uses lazy initialization, meaning elements are only loaded when they are accessed.

By using Page Factory, testers can use annotations like @FindBy, @CacheLookup, and @FindAll to define element locators efficiently. What is Page Factory in Selenium? Simply put, it’s a more streamlined approach to initializing and interacting with web elements, reducing the chances of errors and improving the performance of Selenium tests.

Benefits of Using Page Factory in Selenium

Page Factory in Selenium provides an efficient way to initialize web elements using @FindBy annotations, making the code cleaner and more maintainable. Unlike traditional approaches where locators are declared manually, Page Factory automates the process, ensuring faster element initialization. It follows the concept of lazy initialization, meaning elements are only loaded when they are accessed, which improves memory efficiency and reduces execution time. 

Another key benefit of using Page Factory in Selenium is the ability to use @CacheLookup to cache frequently used web elements, resulting in faster test execution. The Page Factory approach also makes test scripts more readable and maintainable. 

Instead of searching for elements in every test case, you can store locators in the Page Object class, making it easier to handle changes in the UI. 

Step-by-Step Process to Implement Page Object Model (POM) in Selenium with Python

  • Set Up Project Structure
    • Create folders like pages/, tests/, utils/, and config/ to organize page classes, test scripts, utilities, and configuration files.
  • Install Required Libraries
    • Install Selenium and pytest:
      pip install selenium pytest
    • Download and configure a web driver (e.g., ChromeDriver) for browser-based tests.
  • Create Page Classes
    • In the pages/ folder, create a Page Class for each web page.
    • Define web element locators (e.g., By.ID, By.XPATH) and reusable methods (e.g., enter_username(), click_button()) to interact with elements.
  • Set Up Web Driver Utility
    • Create a driver setup file in utils/ to initialize and configure the Selenium WebDriver.
  • Write Test Scripts
    • In the tests/ folder, import the required Page Classes and call their methods in test scripts. Add assertions to validate test outcomes.
  • Use Configuration Files
    • Store global settings like base URLs and credentials in config/ to avoid hardcoding values in scripts.
  • Run Tests and Generate Reports
    • Run tests using pytest.
    • pytest -v  
    • Store test results in a reports/ folder for tracking execution outcomes.

How to Set Up Page Factory in Selenium with Python??

Install Selenium

  • Install Selenium and required libraries:
  • Command: pip install selenium

Set Up Project Structure

  • Create folders for pages/, tests/, utils/, and config/ to separate page classes, test scripts, utilities, and configuration files.

Import Required Modules

  • Import necessary modules like from selenium.webdriver.common.by import By and from selenium.webdriver.support.page_factory import PageFactory in the Page Class.

Create Page Class

  • In the pages/ folder, create a Page Class for each page (e.g., LoginPage) and define web element locators using @FindBy annotations.

Initialize Web Elements with Page Factory

  • Use PageFactory.init_elements() to initialize all the web elements in the class.

Define Actions/Methods

  • Add methods to perform actions like enter_username(), click_login(), etc., for user interactions with the page elements.

Write Test Scripts

  • Import the Page Class in the test script and call the methods to perform tests.

Run Tests Using pytest

  • Execute test scripts using the pytest framework
  • Command: pytest -v

Page Object Model (POM) vs Page Factory: Key Differences You Should Know

Both Page Object Model (POM) and Page Factory aim to improve test automation efficiency. Let’s see the key differences between them in terms of code readability, reusability, and element initialization.

Criteria Page Object Model (POM) Page Factory
Code Repetition Higher, as locators are manually initialized. Reduced, as elements are initialized automatically using @FindBy annotations.
Code Reusability Reusability is achieved through page methods. Reusability is improved as element initialization is automated.
Code Snippet Requires explicit declaration of locators. Uses @FindBy annotations for cleaner and shorter code snippets.
Code Maintainability High maintainability since locators are in one place. Higher maintainability due to automated element initialization.
Code Clarity This is clearer because the page methods are more explicit and self-explanatory. Less clear due to @FindBy annotations that may hide logic details.
Code Complexity Moderate as it follows a clear structure. Slightly complex due to annotations and lazy initialization.
Code Increases The code size may increase if locators are repeated. Code size remains minimal due to automated initialization and annotations.
Code Readability Easy to read as methods are descriptive and explicit. Annotations may affect readability for beginners.

How Page Object Model (POM) Helps in Test Automation Frameworks

The Page Object Model (POM) plays a vital role in creating maintainable and efficient test automation frameworks. It provides a well-structured approach to organizing automation code by separating web element locators and page-specific methods from the actual test logic. 

This makes it easier to manage code updates when changes are made to the UI, as only the Page Class needs to be updated, not the test scripts. 

POM enables the creation of reusable code that can be shared across multiple automation test scenarios, saving time and effort. 

This reusability is especially beneficial for complex data-driven scenarios, where multiple test cases share common page interactions like login, form submissions, or navigation.

POM also supports automated cross-browser testing by allowing seamless execution of tests across different browser environments. It enables testers to define browser capabilities for multiple browser versions, devices, and operating systems. When combined with a cloud-based cross-browser testing platform, POM allows testers to run tests on different combinations of browsers simultaneously, ensuring better coverage and faster execution. 

By encapsulating all actual test scenarios within test scripts and keeping element definitions in Page Classes, POM reduces the time required for maintenance and provides a scalable, modular structure for large-scale test automation.

Is Your App Crashing More Than It's Running?

Boost stability and user satisfaction with targeted testing.

Example of Page Object Model (POM) in Selenium

The Page Object Model (POM) is a structured approach where each web page is represented as a Page Class. This class acts as an object repository for all web elements like buttons, input fields, and links, which are identified using a locator type (e.g., By.ID, By.NAME, or By.XPATH) and a location strategy

Instead of referencing locators directly in test scripts, they are stored in the Page Class, making it easier to maintain the framework. Updates to locators in the Page Class automatically reflect in all related test scripts.

In the POM approach, methods are created to interact with object elements, such as enter_username(), enter_password(), and click_login() on a login screen. Driver objects are used to call these methods, ensuring reusability and reducing maintenance efforts. 

Static methods or instance methods are used to manage load times and handle dynamic elements with wait conditions. By following the POM structure, test automation frameworks become more scalable, maintainable, and readable.

Example of Page Factory in Selenium

The Page Factory in Selenium is an advanced implementation of the Page Object Model (POM), which makes it easier to initialize and interact with web elements. 

Unlike traditional POM, where web elements are defined and initialized manually, Page Factory uses @FindBy annotations to define locators and automatically initializes them using PageFactory.init_elements(). This approach eliminates boilerplate code, enhances readability, and supports lazy initialization, meaning elements are only loaded when they are accessed.

Page Factory is widely used in modern test automation frameworks to reduce maintenance efforts and increase test efficiency. It works well for large-scale web applications where frequent UI changes occur. 

Instead of updating multiple scripts when locators change, testers only need to update the Page Class, making test maintenance simple. 

With support for @CacheLookup, Page Factory speeds up frequently used web elements by caching them, which significantly improves execution speed.

Page Object Model (POM) and Page Factory: When to Use Each Approach??

When to Use Page Object Model (POM)?

The Page Object Model (POM) is best used when you want to have full control over how locators are defined and accessed. It is ideal for testers and developers who prefer a clear, explicit, and simple approach. POM is useful in scenarios where the UI elements remain static or change infrequently. 

Since the locators are declared as instance variables and initialized manually, it offers more control and better readability, making it easier for beginners to understand. POM works well in situations where explicit waits are required, and manual handling of elements is necessary for dynamic elements that load at different times.

When to Use Page Factory?

The Page Factory approach should be used when you want a cleaner, shorter, and more maintainable codebase. It is useful in applications where web elements are frequently reused across multiple test scripts. @FindBy annotations reduce the boilerplate code for locator declarations, while PageFactory.init_elements() automates the initialization process. 

Lazy initialization makes it ideal for large-scale, complex web applications where the loading of web elements can vary. Page Factory is preferred when you want to optimize the test execution speed using @CacheLookup to cache frequently accessed elements, especially in large test suites.

Top Tips for Writing Maintainable Page Object Model (POM) Code

Use Descriptive and Clear Method Names

  • Name your methods clearly (e.g., click_login_button() instead of clickButton()) to improve readability and make the code self-explanatory.

Keep Locators Centralized in the Page Class

  • Store all locators (like By.ID, By.XPATH) at the top of the Page Class to make them easy to update when UI changes occur.

Avoid Hardcoding Values

  • Avoid hardcoding URLs, credentials, and environment details. Use a config file to store them and access them dynamically.

Create Reusable Methods for Common Actions

  • Write reusable methods like enter_text() or click_button() to avoid repetitive code for similar actions.

Use Explicit Waits Instead of Implicit Waits

  • Use explicit waits instead of implicit waits for elements that load dynamically, ensuring your tests are stable and less flaky.

Follow the DRY Principle (Don’t Repeat Yourself)

  • Avoid repeating the same logic across multiple methods or test scripts. Instead, create utility methods for common actions.

Keep Methods Short and Focused

  • Each method should perform a single action, like clicking a button or entering text, to make the code more maintainable and modular.

Frustrated with Frequent App Performance Issues?

Upgrade to seamless speed & reliability with our testing.

Conclusion

In this blog, we explored the Page Object Model (POM) and Page Factory - two essential design patterns in Selenium that improve the maintainability, reusability, and scalability of test automation frameworks. 

We learned how POM encapsulates web elements and actions within Page Classes, following the "separation of concerns" principle, which makes the framework more modular and maintainable. 

On the other hand, Page Factory introduces automation-friendly enhancements like @FindBy annotations and lazy initialization to reduce boilerplate code and improve test efficiency. 

We also highlighted the differences between POM and Page Factory, showing when to use each approach based on project size, complexity, and UI changes.

Additionally, we provided a step-by-step guide for setting up POM and Page Factory in Selenium with Python, including project structure, driver setup, page class creation, and test execution. Key concepts like cross-browser testing, test reusability, and reduced maintenance efforts were also discussed. 

We wrapped it up with real-world example scenarios, like logging into a web application, product search, and checkout workflows. Finally, we shared top tips for writing maintainable POM code, such as keeping locators centralized, following the DRY principle, and ensuring method clarity. By mastering both POM and Page Factory, you can create a robust test automation framework that is scalable, efficient, and easy to maintain.

People also asked

👉Is Selenium Page Factory deprecated?

No, Page Factory is not deprecated. It is still supported in Selenium to improve code readability, reduce boilerplate code, and enable lazy initialization of web elements.

👉What is the factory design pattern in Selenium?

The Factory Design Pattern creates objects dynamically at runtime. In Selenium, it is used in Page Factory to initialize web elements automatically using @FindBy annotations.

👉What is the page component object model?

The Page Component Object Model (PCOM) is an advanced form of POM where reusable components (like headers, footers, or menus) are treated as separate classes to reduce redundancy and enhance maintainability.

👉What is DOM?

The Document Object Model (DOM) represents the structure of a webpage as a tree-like model, where elements (tags) are nodes, allowing Selenium to locate and interact with elements on the page.

👉What is the difference between POM XML and TestNG XML?

POM XML is a Maven configuration file used to manage dependencies and plugins, while TestNG XML defines the test suite, test classes, and execution order for TestNG-based test automation.

Rupesh Garg
Author
Our blog

Latest blog posts

Discover the latest in software testing: expert analysis, innovative strategies, and industry forecasts
Software Testing

The Testing Pyramid: A Guide to Effective Software Testing

Rupesh Garg
Rupesh Garg
December 20, 2024
5 min read
Automation Testing

Mastering Automated UI Testing: Overcoming Common Hurdles

Rupesh Garg
Rupesh Garg
December 20, 2024
5 min read
Automation Testing
Software Testing

Page Object Model and Page Factory in Selenium with Python

Rupesh Garg
Rupesh Garg
December 19, 2024
5 min read