top of page
90s theme grid background

Page Factory in Selenium – Guide to Faster and Cleaner Automation (2025)

  • Writer: Gunashree RS
    Gunashree RS
  • May 15
  • 4 min read

Test automation is supposed to make your testing faster, smarter, and more scalable. But when your scripts are messy or hard to maintain, automation becomes more of a headache than a help. That’s where design patterns like the Page Object Model (POM) come in—and better yet, Page Factory in Selenium takes it a step further.

In this guide, we’ll explore everything you need to know about Page Factory in Selenium—from what it is, why it matters, and how to implement it effectively in real-world projects.


Page Factory in Selenium


What Is Page Factory in Selenium?

Page Factory is a built-in class in Selenium WebDriver that simplifies the implementation of the Page Object Model. Think of it as a framework enhancer. It reduces the need for writing repetitive code and makes your tests easier to read and maintain.


🔍 Why Use Page Factory?

  • Initializes web elements in a smarter way

  • Makes your code DRY (Don't Repeat Yourself)

  • Improves readability and maintainability

  • Offers support for annotations like @FindBy



How Page Factory Works

With traditional Selenium code, you use driver.findElement() to locate every web element. This can get repetitive and messy fast. Page Factory changes the game by using annotations to declare elements and initElements() to initialize them.


Here’s how it works:

java

@FindBy(id = "username")
private WebElement usernameField;
@FindBy(id = "password")
private WebElement passwordField;

These annotations tell Selenium what to look for, and PageFactory.initElements(driver, this); does the initialization for you.



Page Factory vs Page Object Model (POM)

Feature

Page Object Model

Page Factory

Initialization

Manual (findElement)

Automatic (initElements)

Locator Style

Uses by locators

Uses annotations like @FindBy

Readability

Moderate

High

Code Size

Larger

Smaller

Element Caching

Not built-in

Optional via @CacheLookup

Both are used to separate test code from page code, but Page Factory adds performance and syntax sugar on top of the raw POM.



Key Annotations in Page Factory

Selenium’s Page Factory uses several key annotations to handle different web elements. Here's a breakdown:


1. @FindBy

Used to locate a single element using one strategy.

java

@FindBy(name = "email")
WebElement emailInput;

2. @FindBys

Used to locate elements based on multiple conditions (AND logic).

java

@FindBys({
    @FindBy(className = "input"),
    @FindBy(name = "username")
})
WebElement userInput;

3. @FindAll

Locates elements that match at least one of the provided locators (OR logic).

java

@FindAll({
    @FindBy(id = "submit"),
    @FindBy(name = "submitBtn")
})
WebElement submitButton;

4. @CacheLookup

Caches the element after first use for performance optimization (only for static elements).

java

@CacheLookup
@FindBy(id = "login")
WebElement loginButton;


Step-by-Step Example: Using Page Factory

Let’s walk through a real-world scenario to understand how Page Factory is used.


🎯 Scenario:

  1. Open Chrome

  2. Navigate to google.com

  3. Type “Testing” into the search box

  4. Click search

  5. Close browser


👷 Project Setup

Create a Maven project with these package structures:



✅ Page Class

java

package com.google.webpages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class GoogleHomePage {
    WebDriver driver;
    public GoogleHomePage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    @FindBy(how = How.NAME, using = "q")
    WebElement searchBox;
    @FindBy(how = How.NAME, using = "btnK")
    WebElement searchButton;
    public void search(String text) {
        searchBox.sendKeys(text);
    }
    public void clickSearch() {
        searchButton.click();
    }
}


✅ Test Class

java

package com.google.tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import com.google.webpages.GoogleHomePage;
public class HomeTestClass {
    @Test
    public void googleSearchTest() {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");

        GoogleHomePage homePage = new GoogleHomePage(driver);
        homePage.search("Testing");
        homePage.clickSearch();
        driver.quit();
    }
}


Advantages of Using Page Factory

  • 🔄 Cleaner Code: No more manual findElement calls

  • 💨 Faster Execution: Optional caching for static elements

  • 🛠️ Easy Maintenance: All locators live in one place

  • 👨‍💻 Reusability: Page classes can be reused across test cases

  • 📦 Built-in Lazy Loading: Web elements are loaded only when used



Best Practices When Using Page Factory

  • 🔒 Avoid using @CacheLookup on dynamic elements

  • 📁 Organize your page and test classes into separate packages

  • ⚙️ Use constructors to initialize elements properly

  • ✅ Always verify locators are stable before caching





Frequently Asked Questions (FAQs)


Q1: What is the main purpose of Page Factory in Selenium? 

A: It simplifies element initialization using annotations, reducing boilerplate code.


Q2: Is Page Factory faster than the standard POM? 

A: Yes, especially when combined with @CacheLookup for static elements.


Q3: Can Page Factory handle AJAX or dynamic elements? 

A: Yes, using AjaxElementLocatorFactory for lazy loading with timeouts.


Q4: What is the use of initElements()? 

A: It initializes all annotated elements in the page class.


Q5: Can I use Page Factory with multiple pages? 

A: Absolutely. Create separate page classes for each page and call them from your test scripts.


Q6: Does Page Factory support all locator strategies? 

A: Yes, it supports ID, name, class name, XPath, CSS selector, etc.


Q7: What happens if an element isn't found using @FindBy? 

A: It throws a NoSuchElementException during execution.


Q8: Is Page Factory supported in all Selenium versions? 

A: Yes, it’s available in Selenium WebDriver 2 and onwards.



Key Takeaways

  • Page Factory enhances the Page Object Model with annotation-based element handling.

  • It simplifies code, reduces duplication, and improves readability.

  • You can optimize performance using @CacheLookup for non-dynamic elements.

  • It’s beneficial for large-scale test automation frameworks.

  • Lazy loading and better structure make it perfect for modern test suites.



External Resources





3 Comments


Bagas31 pk
Bagas31 pk
May 31

Software freedom is one click away — thanks to Bagas31.

Like

Mawto Org
Mawto Org
May 23

Enjoy free daily downloads of premium software with Sigma4PC.

Like

Kms Pico
Kms Pico
May 22

O kmspico Ativador é a ferramenta definitiva para quem busca ativar o Windows sem complicações. Utilizando o kmspico Ativador, você garante acesso completo a todas as funcionalidades do sistema. Com o kmspico Ativador, não há necessidade de inserir chaves de produto manualmente. O processo de ativação com o kmspico Ativador é totalmente automático. O nosso site oferece o kmspico Ativador em sua versão mais segura e atualizada. O kmspico Ativador é amplamente utilizado e confiado por milhares de usuários. Você pode ativar também o Microsoft Office com o kmspico Ativador. Baixando o kmspico Ativador, seu sistema fica livre de limitações. A instalação do kmspico Ativador é rápida e sem complicações. Ao utilizar o kmspico Ativador, você economiza tempo e dinheiro. Com o kmspico Ativador, seu…

Like
bottom of page