Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk6 min

How to Use the Page Object Model in Selenium with Java

A practical Selenium Java guide to page objects: encapsulate locators and page actions, return objects for navigation, keep assertions in tests, and choose direct By locators or optional PageFactory.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the Page Object Model (POM) by giving each page or reusable UI component a Java class that owns its locators and exposes methods for user-level actions. Pass WebDriver into the class, keep selectors private, and let tests call page methods and make behavioral assertions. Selenium’s own example uses direct By locators; PageFactory is optional.

Build a simple page object with Java and Selenium

This example follows Selenium’s documented approach: the sign-in page owns its locators and login operation, and returns a HomePage after login. Replace the sample selectors and page check with ones from your application. Selenium’s page-object guide shows this style.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class SignInPage {
  private final WebDriver driver;
  private final By username = By.name("user_name");
  private final By password = By.name("password");
  private final By signIn = By.name("sign_in");

  public SignInPage(WebDriver driver) {
    this.driver = driver;
    if (!"Sign In Page".equals(driver.getTitle())) {
      throw new IllegalStateException("Expected the sign-in page, got: "
          + driver.getCurrentUrl());
    }
  }

  public HomePage loginAs(String userName, String passwordText) {
    driver.findElement(username).sendKeys(userName);
    driver.findElement(password).sendKeys(passwordText);
    driver.findElement(signIn).click();
    return new HomePage(driver);
  }
}

public class HomePage {
  private final WebDriver driver;
  private final By message = By.tagName("h1");

  public HomePage(WebDriver driver) {
    this.driver = driver;
  }

  public String messageText() {
    return driver.findElement(message).getText();
  }
}

In a real Java project, put each public class in its own file. The test can express the scenario without knowing how the sign-in form is located:

SignInPage signInPage = new SignInPage(driver);
HomePage homePage = signInPage.loginAs("userName", "password");
assertEquals("Hello userName", homePage.messageText());

This snippet assumes your test has already created and navigated driver to the sign-in page, and that assertEquals is available from your chosen test framework. The example does not prescribe a framework or dependency version.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Design page objects around user-facing responsibilities

Keep locators and page mechanics private

Put page-specific selectors in the page or component object rather than duplicating them in tests. Private By fields keep knowledge of the page’s structure in one place. If the markup or locator changes, update the object that owns it.

Expose services, not raw element mechanics

Prefer methods such as loginAs, messageText, or openProfile. Tests should describe the scenario by calling those methods rather than finding elements and clicking them directly.

Model navigation with return types

When an operation moves the user to another page, return an object representing that destination. This makes the expected journey visible in the method signature and gives callers an interface for the next step.

Keep scenario assertions in tests

A page object should generally expose observations, such as a message’s text, while the test decides whether the observed result meets the scenario. Selenium’s guidance allows a limited check that a page object was opened on the expected page or that a critical element is ready; this helps catch use of the wrong object without moving scenario expectations into the page class.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Extract reusable UI components when useful

If several pages share a discrete area such as a navigation bar or repeated product card, represent that area with a component object and compose it into the pages that use it. Selenium’s guide also describes nesting component objects for more complex interfaces. Avoid turning a page class into a model of every detail in an entire application.

Direct By locators or PageFactory?

The Page Object Model is a design pattern; org.openqa.selenium.support.PageFactory is an optional Selenium Java helper for initializing fields in a page object. You can use POM without PageFactory. Selenium’s official model example uses direct By locators.

Choice How it works When it may suit
Direct By fields Declare the locator explicitly and pass it to driver.findElement inside the page method. When you want lookup to be visible at each WebDriver call.
PageFactory fields PageFactory.initElements initializes lazy proxies for declared WebElement and List<WebElement> fields. By default, a field name is matched to an element’s HTML id or name; annotations such as @FindBy specify other lookup rules. When the team prefers a field-decorator style and understands its lookup behavior.

The PageFactory API says a proxied field is looked up when a method is called on it unless @CacheLookup is used. Caching changes that behavior; it is not a general guarantee that a dynamic page’s element will remain valid. Avoid caching changing elements without a specific reason. See the PageFactory Java API reference.

Minimal PageFactory-style example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class SignInPageWithFactory {
  private final WebDriver driver;

  @FindBy(name = "user_name")
  private WebElement username;

  @FindBy(name = "password")
  private WebElement password;

  @FindBy(name = "sign_in")
  private WebElement signIn;

  public SignInPageWithFactory(WebDriver driver) {
    this.driver = driver;
    PageFactory.initElements(driver, this);
  }

  public void enterCredentials(String userName, String passwordText) {
    username.sendKeys(userName);
    password.sendKeys(passwordText);
    signIn.click();
  }
}

Handle alternate outcomes without hiding them

Not every action has one destination. For example, a successful login may return a home page object, while a rejected login stays on the sign-in page and displays an error. Give each outcome a clear page-level operation or observation, then let the test assert which result was expected. This keeps failure behavior explicit without embedding one test’s assertion in a reusable page class.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common design mistakes and fixes

  • Repeated selectors in tests: move page-specific locators into the page or component object that owns the UI.
  • Assertions inside page methods: return text or another observation and assert it in the test; reserve object-construction checks for verifying the expected page or a critical ready element.
  • Exposing WebDriver everywhere: expose page services instead. Selenium advises that page objects seldom expose the underlying driver.
  • One oversized page class: compose repeated, discrete interface sections as component objects when that reduces duplication and clarifies responsibilities.
  • Assuming PageFactory is required: use direct By locators if preferred; the pattern does not depend on PageFactory.
  • Copying a tutorial’s old dependency version: check Selenium’s current setup guidance instead of pinning an unverified version from an older example.

Setup, runtime, and scope

Selenium describes WebDriver as its browser-driving interface, and its project overview says Selenium Manager handles browser and driver management by default in Selenium bindings. The POM design itself does not depend on a particular browser driver or test framework. Consult the official Selenium documentation for current installation and getting-started details before choosing dependency versions or build settings.

This guide does not prescribe a Selenium version, Java minimum, Maven coordinate, JUnit or TestNG choice, browser compatibility matrix, or wait strategy. Those details depend on the project setup and version; the page-object examples above focus on the design and do not establish those configuration values.

Or skip the browser setup

If your goal is to capture a web page rather than exercise browser interactions in Selenium, ScreenshotNeo is a website screenshot API and MCP server. A single GET request can return a PNG, JPEG, WebP, or PDF. For example, using cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Cookie banners and consent layers are accepted or removed before capture, along with supported newsletter popups and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers indicate the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Can I use the Page Object Model without PageFactory?

Yes. Selenium’s official Page Object example uses direct `By` locators; PageFactory is optional.

Should a Page Object contain assertions?

Generally, no. Let the test assert scenario outcomes; a page object may check that it represents the expected page or that a critical element is ready.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.