• Articles

Page Factory in Selenium - A Detailed Guide

Page Factory in Selenium - A Detailed Guide

But what exactly is Page Factory in Selenium, and how can it benefit your testing process? In this detailed guide, we’ll dive deep into the world of Page Factory in Selenium, covering everything you need to know to get started. We’ll explore what Page Factory is, why it’s useful, and how to initialize it in your testing code using Python. We’ll also cover best practices for using Page Factory effectively, including how to manage page objects and how to write efficient and maintainable code. So if you’re looking to take your web automation testing process to the next level, you won’t want to miss this detailed guide to Page Factory in Selenium.

Take your Selenium skills to the next level – Check out our exclusive YouTube video on Selenium training, now featured on our blog!

Video Thumbnail

What is Page Factory in Selenium and Why Do We Use It?

Selenium uses the Page Factory design pattern to initialize web elements automatically in a page object model framework. The main aim of using it is to make the code simpler and easier to maintain. As the Page Factory initializes a page class’s elements without using the FindBy annotation, the code is simpler to read and understand.

In a page object model framework, page objects represent web pages. Thus, Page Factory is used to build these page objects. When interacting with a web page, page objects are web elements. We can automatically initialize the web components of a page object by using Page Factory, which cuts down on the amount of code we need to write and makes it simpler to maintain.

How Page Factory Works

How Page Factory Works
  • Selenium Page Factory Method
    The Page Factory Method is a technique for automatically initializing the web components of a page object. It helps to streamline the code and make it simpler to maintain. It is a component of the Page Factory design pattern.
  • How to Set Up the Selenium Page Factory
    Here is a detailed tutorial on how to set up Page Factory in Selenium

    Make a page object class first, then declare the web elements within it.
    Find the web elements by using the @FindBy annotation.
    Use the PageFactory.initElements() method to initialize web elements automatically.
public class LoginPage {
     @FindBy(name = "username")
    WebElement usernameInput;
     @FindBy(name = "password")
     WebElement passwordInput;
     @FindBy(css = "button[type='submit']")
    WebElement loginButton;
     public LoginPage(WebDriver driver) {
         PageFactory.initElements(driver, this);
    }
    public void login(String username, String password) {
        usernameInput.sendKeys(username);
         passwordInput.sendKeys(password);
        loginButton.click();
     }
}

Get 100% Hike!

Master Most in Demand Skills Now!

Advantages of Using Page Factory in Selenium

Selenium’s Page Factory implementation has several benefits, making it a well-liked design pattern for creating compelling and enduring test scripts. It lessens code duplication, boosts code maintainability, increases test script readability, and increases test script reuse and stability. Understanding and adapting the test script is simpler since Page Factory separates the test script from the implementation details by enclosing the initialization of web elements in a Page Object Model.

Selenium’s Page Factory design pattern is well-liked for creating effective and enduring test scripts due to its many benefits. Some of the main benefits are as follows

  • Less code duplication – By building an object repository for web elements in a web page, Page Factory helps to lessen code duplication. This implies that you do not need to manually create the code in each test script to locate each web element.
  • Improves code maintainability – Page Factory offers a mechanism to encapsulate the initialization of web elements in a Page Object Model, which enhances code maintainability. It follows that any changes to the UI or structure of a web page will only affect the Page Object Model and not every test script that depends on it. This makes it easier to maintain your test scripts over time.
  • Makes test scripts easier to read – By using Page Factory, you can make test scripts easier to read. The test script is simpler to comprehend and alter since the Page Object Model clearly separates the test script from the implementation’s underpinnings.
  • Improves test script reuse – By using Page Factory to produce a Page Object Model, several test scripts can use the same Page Object Model at once, cutting down on development time and making it simpler to construct new test scripts.
  • Increases test script stability – By lowering the possibility of false negatives brought on by timing issues or improper element recognition, Page Factory can assist in increasing the strength of your test scripts.

Why We Use Page Factory in Selenium

There are several advantages to using Page Factory in Selenium. Some of the main benefits include:

  • Better Readability – Thanks to Page Factory, your test scripts are simple to read and keep up with. Using Page Factory, you can establish a distinct division between your test logic and your page elements.
  • Enhanced Maintainability – Your test scripts are simple to maintain with Page Factory. You can modify your page elements using Page Factory without adjusting your test logic.
  • Greater Usability – Your test scripts can be reused with ease using Page Factory. Using Page Factory, you may build a library of Page Object classes that various test scripts can utilize.

Page Factory in Selenium Python

Python is one of the many programming languages that Page Factory is compatible with. Initializing the web components in a Page Object Model (POM) in Python requires the use of Page Factory. The ‘webdriver’ and ‘support’ packages must be imported in Selenium with Python in order to use Page Factory. The Page Factory may then be used to generate a Page Object Model in and initialize it.

Here’s an example of how to initialize Page Factory in Selenium with Python:

python

from selenium import webdriver
from selenium.webdriver.support.page_factory import PageFactory
class LoginPage:
    def __init__(self, driver):
        self.driver = driver
        PageFactory.init_elements(driver, self)
    username = driver.find_element_by_name("username")
    password = driver.find_element_by_name("password")
    login_button = driver.find_element_by_name("login")
    def login(self, username, password):
        self.username.send_keys(username)
        self.password.send_keys(password)
        self.login_button.click()

In the above-mentioned example, we developed a LoginPage class that includes the web elements and login method. Using the ‘init_elements’ method of Page Factory, we have initialized the web elements.

How to Initialize Page Factory in Selenium?

How to Initialize Page Factory in Selenium

You must initialize Page Factory in Selenium before using it. You can do it by following the procedures listed below.

  • Make a WebDriver instance
    You must first establish an instance of the WebDriver interface before you can initialize Page Factory. Any browser will work to generate a WebDriver instance. For instance, you may use the following code to establish a Chrome browser instance:
from selenium import webdriver
driver = webdriver.Chrome()
  • Establish a Page Object Class
    You must build a Page Object class after creating an instance of the WebDriver interface. A web page or a piece of a web page is represented by a class called a “Page Object.” Using the following code, you can create a Page Object class.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class HomePage:
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(self.driver, 10)
        self.search_box = self.wait.until(EC.presence_of_element_located((By.NAME, "q")))
        self.search_button = self.driver.find_element(By.NAME, "btnK")

We’ve generated a Page Object class in the code above for the Google home page. The class contains the “search_box” and “search_button” elements, which are the search box and search button on the Google site, respectively.

  • Initialize Page Factory
    You can initialize Page Factory once you’ve created a Page Object class. The following code will initialize Page Factory for you.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.pagefactory import PageFactory
class HomePage:
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(self.driver, 10)
        PageFactory.initElements(self.driver, self)
    @FindBy(name = "q")
    private WebElement search_box;
    @FindBy(name = "btnK")
    private WebElement search_button;

We’ve initialized Page Factory for the Google homepage in the code above. The elements in the ‘HomePage’ class have been initialized using the ‘initElements()’ function of the PageFactory class.

Conclusion

Page Factory is a powerful and valuable feature in Selenium that provides an easy and efficient way to create and maintain automated tests. With Page Factory, you can improve the readability and maintainability of your Selenium code by using a design pattern that emphasizes object-oriented programming principles. This feature allows you to create a class representing a web page and define elements on that page as class variables. Doing so will enable you to easily reuse these elements throughout your test cases, making your code more modular and less prone to errors. This article will explore what Page Factory is, why it is essential in Selenium, how to initialize it in Python, and how to use it effectively to write robust and maintainable automated tests.

Course Schedule

Name Date Details
Testing Courses 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch