</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

What is Page Factory in Selenium?

Page Factory is an implementation of POM that uses @FindBy annotations and PageFactory.initElements() to initialize web elements.

Answer

Page Factory is an implementation of Page Object Model in Selenium. It provides:

  • @FindBy annotation to declare web elements
  • PageFactory.initElements() method to initialize all elements annotated with @FindBy

Benefits over plain POM:

  • Cleaner, annotation-based syntax
  • Elements are lazily initialized (looked up when first used)
  • No need to write driver.findElement(By...) repeatedly

Full Page Factory example:

Java
public class SamplePage {

    WebDriver driver;

    @FindBy(id = "search")
    WebElement searchTextBox;

    @FindBy(name = "searchBtn")
    WebElement searchButton;

    // Constructor
    public SamplePage(WebDriver driver) {
        this.driver = driver;
        // initElements method initializes all @FindBy elements
        PageFactory.initElements(driver, this);
    }

    // Sample method
    public void search(String searchTerm) {
        searchTextBox.sendKeys(searchTerm);
        searchButton.click();
    }
}

Using the page in a test:

Java
SamplePage page = new SamplePage(driver);
page.search("Selenium WebDriver");

Other @FindBy locator strategies:

Java
@FindBy(xpath = "//button[@type=''submit'']")
@FindBy(css = ".btn-primary")
@FindBy(linkText = "Click Here")
@FindBy(tagName = "input")

Follow AutomateQA

Related Topics