Popular Searches
Popular Course Categories
Popular Courses

Locators in Page Classes

Locators in Page Classes

Page Object Model

Locators in Page Classes

Locators in Page Classes are one of the most important concepts in the Page Object Model (POM) used with Selenium WebDriver. A locator identifies a specific web element on a web page so that Selenium can interact with it, such as clicking a button, entering text, selecting an option, reading text, or validating an element.

In a Page Object Model framework, locators are normally maintained inside Page Classes instead of being scattered throughout test classes. This keeps Selenium element-identification logic organized, reusable, and easier to maintain when the application UI changes.

JustAcademy's Selenium training curriculum includes Selenium WebDriver, locators, XPath and CSS selectors, TestNG, Page Object Model, data-driven testing, and automation framework concepts. :contentReference[oaicite:0]{index=0}

Course Resource: Selenium Training | Register for Course Demo


1. What are Locators?

A locator is a mechanism used by Selenium WebDriver to identify a particular HTML element on a web page. Selenium needs a reliable way to find an element before performing an action on it.

For example, consider a login page containing a username field:

<input id="username" name="username" type="text">

Selenium can locate this element using its id attribute:

driver.findElement(By.id("username")).sendKeys("admin");

The locator tells Selenium exactly which element should receive the action.


2. Why are Locators Important in Page Classes?

Locators form the connection between the Page Object and the actual web page. A Page Class generally contains the locators and methods that operate on those elements.

  • Centralizes element identification.
  • Reduces duplicate locator code.
  • Makes test classes cleaner.
  • Improves framework maintainability.
  • Makes UI changes easier to handle.
  • Encourages reusable page methods.
  • Separates page interaction logic from test logic.
  • Improves readability of automation scripts.
  • Supports scalable Selenium frameworks.


3. Locator Flow in Page Object Model

Test Class

    |

    v

Page Class

    |

    v

Locator

    |

    v

Web Element

    |

    v

Selenium WebDriver

    |

    v

Browser

    |

    v

Web Application

The test class calls a page method. The page method uses a locator to find the required web element and Selenium performs the browser interaction.


4. Selenium Locator Strategies

Selenium provides several commonly used locator strategies for identifying elements.

LocatorExampleTypical Usage
idBy.id("username")Element with unique ID
nameBy.name("email")Element with name attribute
classNameBy.className("login-btn")Element with class name
tagNameBy.tagName("button")Elements identified by tag
linkTextBy.linkText("Login")Exact link text
partialLinkTextBy.partialLinkText("Log")Partial link text
cssSelectorBy.cssSelector("#username")CSS-based element identification
XPathBy.xpath("//input[@id='username']")Flexible element identification


5. Using By Locators in Page Classes

In a Page Class, locators can be declared as variables of type By.

import org.openqa.selenium.By;

 

public class LoginPage {

 

    private By username = By.id("username");

    private By password = By.id("password");

    private By loginButton = By.id("loginButton");

}

This approach keeps the locator definitions in one place.


6. Creating a Basic Login Page Class

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class LoginPage {

 

    private WebDriver driver;

 

    private By username = By.id("username");

    private By password = By.id("password");

    private By loginButton = By.id("loginButton");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String value) {

        driver.findElement(username).sendKeys(value);

    }

 

    public void enterPassword(String value) {

        driver.findElement(password).sendKeys(value);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton).click();

    }

}


7. ID Locator in Page Classes

The id locator is commonly used when an element has a unique and stable ID.

<input id="username" type="text">

Page Class:

private By username = By.id("username");

Usage:

driver.findElement(username).sendKeys("admin");

When IDs are unique and stable, they can provide simple and readable locators.


8. Name Locator in Page Classes

The name locator can be used when an element contains a useful name attribute.

<input name="email" type="text">

private By email = By.name("email");

Interaction:

driver.findElement(email).sendKeys("[email protected]");


9. Class Name Locator

The className locator identifies an element using its class attribute.

<button class="login-button">Login</button>

private By loginButton = By.className("login-button");

Be careful when the element contains multiple class names. By.className() expects a single class name, not a space-separated collection of classes.


10. Tag Name Locator

The tagName locator identifies elements based on HTML tags such as input, button, a, div, or select.

private By button = By.tagName("button");

Tag names are often less specific because a page may contain many elements with the same tag. Therefore, they should generally be used when the target element can be identified reliably.


11. Link Text Locator

linkText is used for links where the complete visible text is known.

<a href="/login">Login</a>

private By loginLink = By.linkText("Login");


12. Partial Link Text Locator

partialLinkText can identify a link using part of its visible text.

<a href="/products">View All Products</a>

private By productsLink = By.partialLinkText("Products");

Partial link text should be used carefully if multiple links contain the same text fragment.


13. CSS Selector in Page Classes

CSS selectors are widely used in Selenium Page Classes because they provide concise and flexible element identification.

private By username = By.cssSelector("#username");

private By password = By.cssSelector("#password");

private By loginButton = By.cssSelector(".login-button");

Example HTML:

<input id="username">

<input id="password">

<button class="login-button">Login</button>


14. XPath in Page Classes

XPath is another powerful locator strategy used to identify elements based on attributes, text, hierarchy, relationships, and other conditions.

private By username = By.xpath("//input[@id='username']");

private By password = By.xpath("//input[@id='password']");

private By loginButton = By.xpath("//button[@id='loginButton']");


15. Relative XPath

Relative XPath usually begins with // and allows an element to be located using attributes or relationships.

private By username = By.xpath("//input[@name='username']");

Relative XPath is commonly used in Page Classes because it can identify elements without depending on the complete HTML document hierarchy.


16. XPath Using Text

An element can sometimes be located using its visible text.

private By loginButton = By.xpath("//button[text()='Login']");

For example:

<button>Login</button>

The XPath identifies the button whose text is exactly "Login".


17. XPath Using Contains

The contains() function is useful when an attribute value is partially known.

private By loginButton =

    By.xpath("//button[contains(@class,'login')]");

Example:

<button class="primary-login-button">Login</button>


18. XPath Using Multiple Attributes

Multiple attributes can be combined when one attribute alone does not uniquely identify the element.

private By username =

    By.xpath("//input[@type='text' and @name='username']");


19. CSS Attribute Selector

CSS selectors can also use HTML attributes.

private By username =

    By.cssSelector("input[name='username']");

Another example:

private By loginButton =

    By.cssSelector("button[id='loginButton']");


20. CSS Class Selector

A CSS class selector starts with a period.

private By loginButton =

    By.cssSelector(".login-button");

For multiple classes:

private By submitButton =

    By.cssSelector("button.primary.submit");


21. CSS ID Selector

A CSS ID selector starts with #.

private By username =

    By.cssSelector("#username");

This is equivalent to:

private By username =

    By.id("username");


22. Storing Locators as private Variables

A good Page Class generally keeps locator variables private so that tests interact with the page through meaningful methods instead of directly manipulating locators.

private By username = By.id("username");

private By password = By.id("password");

private By loginButton = By.id("loginButton");

This supports encapsulation and keeps page implementation details inside the Page Class.


23. Locator Naming Conventions

Meaningful locator names make Page Classes easier to understand.

Good examples:

private By usernameField = By.id("username");

private By passwordField = By.id("password");

private By loginButton = By.id("loginButton");

private By forgotPasswordLink = By.linkText("Forgot Password?");

private By errorMessage = By.cssSelector(".error-message");

Avoid unclear names such as:

private By element1;

private By button2;

private By obj;

private By test;


24. Locator Variables vs WebElement Variables

Locators and WebElements are related but different concepts.

LocatorWebElement
Describes how to find an elementRepresents an element found on the page
Usually stored as ByStored as WebElement
Can be used repeatedly to locate elementsRepresents a specific element reference
Useful for dynamic pagesCan become stale after DOM changes

Example locator:

private By username = By.id("username");

Example WebElement:

WebElement usernameField =

    driver.findElement(username);


25. Using @FindBy in Page Classes

Selenium Page Objects can also use the @FindBy annotation to define WebElements.

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.FindBy;

 

@FindBy(id = "username")

private WebElement usernameField;

 

@FindBy(id = "password")

private WebElement passwordField;

 

@FindBy(id = "loginButton")

private WebElement loginButton;

These elements are commonly initialized using Selenium's PageFactory mechanism.


26. PageFactory Initialization

When using PageFactory-style Page Objects, the Page Class can initialize its annotated elements.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.support.PageFactory;

 

public class LoginPage {

 

    private WebDriver driver;

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

        PageFactory.initElements(driver, this);

    }

}


27. @FindBy with Multiple Locator Types

@FindBy supports different locator strategies.

@FindBy(id = "username")

private WebElement username;

 

@FindBy(name = "password")

private WebElement password;

 

@FindBy(css = ".login-button")

private WebElement loginButton;

 

@FindBy(xpath = "//a[text()='Forgot Password?']")

private WebElement forgotPassword;


28. Complete Login Page Class Using By

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class LoginPage {

 

    private WebDriver driver;

 

    private By usernameField = By.id("username");

    private By passwordField = By.id("password");

    private By loginButton = By.id("loginButton");

    private By errorMessage = By.cssSelector(".error-message");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String username) {

        driver.findElement(usernameField).sendKeys(username);

    }

 

    public void enterPassword(String password) {

        driver.findElement(passwordField).sendKeys(password);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton).click();

    }

 

    public String getErrorMessage() {

        return driver.findElement(errorMessage).getText();

    }

 

    public void login(String username, String password) {

        enterUsername(username);

        enterPassword(password);

        clickLogin();

    }

}


29. Using the Login Page Class in a Test

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    @Test

    public void validLoginTest() {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.get("https://example.com/login");

 

            LoginPage loginPage = new LoginPage(driver);

 

            loginPage.login("admin", "admin123");

        } finally {

            driver.quit();

        }

    }

}

The test does not directly know how the username field, password field, or login button is located. Those implementation details remain inside LoginPage.


30. Locators for Navigation Menus

Page Classes can store locators for navigation links and menu items.

private By homeLink = By.linkText("Home");

private By productsLink = By.linkText("Products");

private By ordersLink = By.linkText("Orders");

private By profileLink = By.linkText("Profile");

private By logoutLink = By.linkText("Logout");

Corresponding methods can hide the locator details:

public void openProducts() {

    driver.findElement(productsLink).click();

}

 

public void openOrders() {

    driver.findElement(ordersLink).click();

}

 

public void logout() {

    driver.findElement(logoutLink).click();

}


31. Locators for Forms

Form Page Classes commonly contain locators for text fields, dropdowns, checkboxes, radio buttons, and submit buttons.

private By firstName = By.id("firstName");

private By lastName = By.id("lastName");

private By email = By.id("email");

private By mobile = By.id("mobile");

private By country = By.id("country");

private By terms = By.id("terms");

private By submitButton = By.id("submit");


32. Locators for E-Commerce Pages

Product and shopping pages can have Page Classes containing locators for product names, prices, quantity fields, cart buttons, checkout buttons, and other controls.

private By productSearch = By.id("search");

private By searchButton = By.id("searchButton");

private By firstProduct = By.cssSelector(".product-card");

private By addToCart = By.cssSelector(".add-to-cart");

private By cartIcon = By.cssSelector(".cart-icon");

private By checkoutButton = By.id("checkout");


33. Locators for Dynamic Elements

Modern web applications frequently generate dynamic IDs and class values. In such situations, the locator should focus on stable attributes or relationships.

Example:

<button id="login_849302">Login</button>

A hard-coded dynamic ID may be unreliable:

By.id("login_849302");

A more flexible locator could be:

By.xpath("//button[starts-with(@id,'login_')]");

The exact strategy should depend on the application's DOM and which attributes remain stable.


34. Avoiding Fragile Locators

Fragile locators are locators that depend heavily on implementation details that frequently change.

Example of a fragile absolute XPath:

/html/body/div[2]/div[1]/div[3]/form/div[2]/input

A more maintainable locator may use a stable attribute:

By.id("username");

or:

By.xpath("//input[@name='username']");


35. Absolute XPath vs Relative XPath

Absolute XPathRelative XPath
Starts from the root of the documentUsually starts with //
Highly dependent on page structureCan focus on attributes and relationships
More fragileGenerally more maintainable
Can break after layout changesCan remain stable when suitable attributes remain unchanged


36. Locator Strategy for Page Classes

A practical locator strategy is to first look for a unique and stable attribute.

  1. Check for a unique ID.
  2. Check for a stable name attribute.
  3. Use a reliable CSS selector.
  4. Use XPath when relationships or text are needed.
  5. Avoid unnecessary absolute XPath.
  6. Avoid relying on unstable generated attributes.
  7. Keep locators readable.


37. Locator and Page Method Separation

A strong Page Object separates locator definitions from the actions performed on those elements.

private By username = By.id("username");

private By password = By.id("password");

private By loginButton = By.id("loginButton");

 

public void login(String user, String pass) {

    driver.findElement(username).sendKeys(user);

    driver.findElement(password).sendKeys(pass);

    driver.findElement(loginButton).click();

}

The locator section describes where an element is, while the page method describes what should be done with it.


38. Encapsulation in Page Classes

Encapsulation is an important principle of POM. Locator variables can remain private while public methods expose meaningful page operations.

private By username = By.id("username");

 

public void enterUsername(String value) {

    driver.findElement(username).sendKeys(value);

}

The test calls:

loginPage.enterUsername("admin");

Instead of:

driver.findElement(By.id("username")).sendKeys("admin");


39. Locators and Explicit Waits

Page Classes can combine locators with explicit waits to make interactions more reliable when elements appear asynchronously.

private By loginButton = By.id("loginButton");

 

public void clickLogin() {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    wait.until(

        ExpectedConditions.elementToBeClickable(loginButton)

    ).click();

}

This approach is particularly useful for modern applications where elements may not be immediately ready for interaction.


40. Locators for Error Messages

Error and validation messages should also be maintained as Page Class locators.

private By loginError =

    By.cssSelector(".login-error");

 

public String getLoginError() {

    return driver.findElement(loginError).getText();

}

Test class:

String error = loginPage.getLoginError();

 

Assert.assertEquals(error, "Invalid username or password");


41. Locators for Tables

Tables often require XPath or CSS selectors that identify rows and cells dynamically.

private By userTable =

    By.cssSelector("table.users");

 

private By userRows =

    By.cssSelector("table.users tbody tr");

For a specific row:

private By adminRow =

    By.xpath("//table[@class='users']//tr[td[text()='admin']]");


42. Locators for Checkboxes

private By termsCheckbox =

    By.id("terms");

 

public void acceptTerms() {

    driver.findElement(termsCheckbox).click();

}

For dynamic state handling, the Page Class can check whether the checkbox is already selected before clicking it.


43. Locators for Radio Buttons

private By maleRadio =

    By.id("male");

 

private By femaleRadio =

    By.id("female");

 

public void selectMale() {

    driver.findElement(maleRadio).click();

}

 

public void selectFemale() {

    driver.findElement(femaleRadio).click();

}


44. Locators for Dropdowns

A dropdown can be identified using a stable locator and then handled with Selenium's Select class when it is a standard HTML select element.

private By countryDropdown =

    By.id("country");

Example:

Select country =

    new Select(driver.findElement(countryDropdown));

 

country.selectByVisibleText("India");


45. Locators for Buttons

Buttons can be located using ID, CSS, XPath, class, or other stable attributes.

private By submitButton =

    By.cssSelector("button[type='submit']");

 

private By cancelButton =

    By.xpath("//button[text()='Cancel']");


46. Locators for Multiple Similar Elements

When multiple elements have similar attributes, the locator should identify the intended element using additional conditions.

private By firstProduct =

    By.cssSelector(".product-card:nth-child(1)");

 

private By secondProduct =

    By.cssSelector(".product-card:nth-child(2)");

For reusable frameworks, it may be better to create methods that accept an index or product name instead of creating many individual locators.


47. Dynamic Locator Method

When a page contains many elements following the same structure, a Page Class can create a locator dynamically.

public By productByName(String productName) {

    return By.xpath(

        "//div[@class='product-card']//h3[text()='"

        + productName

        + "']"

    );

}

Usage:

driver.findElement(

    productByName("Laptop")

).click();

For production frameworks, dynamically constructed locators should be carefully designed and escaped when user-controlled values are involved.


48. Locators with WebDriver Actions

Locators can also be used with Selenium's Actions API for hover, drag-and-drop, and other advanced interactions.

private By menu =

    By.id("productsMenu");

 

WebElement menuElement =

    driver.findElement(menu);

 

Actions actions = new Actions(driver);

 

actions.moveToElement(menuElement).perform();


49. Locators for Frames

A Page Class can store a frame locator when the page interaction requires switching into an iframe.

private By paymentFrame =

    By.id("paymentFrame");

 

public void switchToPaymentFrame() {

    driver.switchTo().frame(

        driver.findElement(paymentFrame)

    );

}


50. Locators for Windows and Tabs

For multiple windows or tabs, the Page Class can provide methods for actions that identify the target page, although window handles themselves are managed through WebDriver.

private By openReport =

    By.id("openReport");

 

public void openReport() {

    driver.findElement(openReport).click();

}


51. Locators for Alerts

Browser alerts are not normal DOM elements, so they are handled through WebDriver's alert API rather than regular element locators.

public void acceptAlert() {

    driver.switchTo().alert().accept();

}

This distinction is important when designing Page Classes.


52. Page Class Example with Multiple Locators

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class RegistrationPage {

 

    private WebDriver driver;

 

    private By firstName = By.id("firstName");

    private By lastName = By.id("lastName");

    private By email = By.id("email");

    private By mobile = By.id("mobile");

    private By password = By.id("password");

    private By submitButton =

        By.cssSelector("button[type='submit']");

    private By successMessage =

        By.cssSelector(".success-message");

 

    public RegistrationPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void register(

        String first,

        String last,

        String emailValue,

        String mobileValue,

        String passwordValue) {

 

        driver.findElement(firstName).sendKeys(first);

        driver.findElement(lastName).sendKeys(last);

        driver.findElement(email).sendKeys(emailValue);

        driver.findElement(mobile).sendKeys(mobileValue);

        driver.findElement(password).sendKeys(passwordValue);

        driver.findElement(submitButton).click();

    }

 

    public String getSuccessMessage() {

        return driver.findElement(successMessage).getText();

    }

}


53. Locator Strategy for Maintainable Frameworks

A maintainable Page Class should prefer stable, meaningful, and readable locators.

Preferred ApproachReason
Unique stable IDSimple and readable
Stable data attributeUseful for automation-specific selectors
Stable CSS selectorConcise and flexible
Relative XPathUseful for relationships and text
Absolute XPathGenerally more fragile


54. Using data-testid Attributes

Some applications provide dedicated automation attributes such as data-testid.

<button data-testid="login-button">Login</button>

Locator:

private By loginButton =

    By.cssSelector("[data-testid='login-button']");

Dedicated test attributes can provide stable selectors when the application team intentionally maintains them for automated testing.


55. Locator Duplication Problem

Without Page Classes, the same locator may appear in many test classes.

driver.findElement(By.id("username"));

driver.findElement(By.id("username"));

driver.findElement(By.id("username"));

driver.findElement(By.id("username"));

If the ID changes, multiple files may need modification.

With POM, the locator can be centralized:

private By username =

    By.id("username");

Only the Page Class needs to be updated when the locator changes.


56. Before and After Page Object Model

Without POM:

@Test

public void loginTest() {

    driver.findElement(By.id("username"))

        .sendKeys("admin");

 

    driver.findElement(By.id("password"))

        .sendKeys("admin123");

 

    driver.findElement(By.id("loginButton"))

        .click();

}

With POM:

@Test

public void loginTest() {

    loginPage.login("admin", "admin123");

}

The second approach keeps test intent clearer and moves UI implementation details into the Page Class.


57. Locators and Reusability

A Page Class should expose reusable business-level actions rather than forcing every test to know individual element locators.

loginPage.login("admin", "admin123");

loginPage.logout();

searchPage.searchFor("Laptop");

cartPage.checkout();

This makes test scripts easier to read and maintain.


58. Common Locator Mistakes

  • Using absolute XPath unnecessarily.
  • Using unstable generated IDs.
  • Using overly long CSS selectors.
  • Using partial link text when multiple links match.
  • Using className with multiple space-separated classes.
  • Duplicating the same locator across test classes.
  • Making locator variables public unnecessarily.
  • Using locators that depend heavily on page layout.
  • Ignoring stable application-specific attributes.
  • Using indexes without understanding their stability.


59. Best Practices for Locators in Page Classes

  • Keep locators inside Page Classes.
  • Use meaningful locator variable names.
  • Prefer stable and unique attributes.
  • Use IDs when they are stable and unique.
  • Use CSS selectors for concise element identification.
  • Use XPath when text or element relationships are required.
  • Avoid unnecessary absolute XPath.
  • Avoid fragile DOM-based locators.
  • Keep locator variables private.
  • Expose page actions through public methods.
  • Use explicit waits for elements that require synchronization.
  • Keep test logic separate from page interaction logic.
  • Use dedicated test attributes when the application provides them.
  • Review locator stability whenever the UI changes.


60. Locator Maintenance Process

Application UI Changes

        |

        v

Identify Broken Locator

        |

        v

Update Page Class

        |

        v

Run Related Tests

        |

        v

Validate Page Methods

        |

        v

Execute Regression Suite

One of the major benefits of POM is that UI locator changes can often be handled inside the relevant Page Class without modifying every test case.


61. Practical Project Structure

src

|-- test

    |-- java

        |-- pages

        |   |-- LoginPage.java

        |   |-- HomePage.java

        |   |-- SearchPage.java

        |   |-- ProductPage.java

        |   |-- CartPage.java

        |   |-- CheckoutPage.java

        |

        |-- tests

        |   |-- LoginTest.java

        |   |-- SearchTest.java

        |   |-- ProductTest.java

        |   |-- CheckoutTest.java

        |

        |-- utilities

            |-- DriverFactory.java

            |-- WaitUtility.java

            |-- ConfigReader.java


62. Complete POM Locator Architecture

Test Class

     |

     | Calls

     v

Page Class

     |

     | Contains

     v

Locators

     |

     | Finds

     v

WebElements

     |

     | Controlled by

     v

Selenium WebDriver

     |

     v

Browser

     |

     v

Web Application


63. Real-World Login Framework Example

A practical Selenium framework can organize login automation into a Page Class and a Test Class.

LoginPage.java

public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    private By loginButton =

        By.id("loginButton");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(

        String usernameValue,

        String passwordValue) {

 

        driver.findElement(username)

            .sendKeys(usernameValue);

 

        driver.findElement(password)

            .sendKeys(passwordValue);

 

        driver.findElement(loginButton)

            .click();

    }

}

LoginTest.java

public class LoginTest {

 

    @Test

    public void loginTest() {

 

        LoginPage loginPage =

            new LoginPage(driver);

 

        loginPage.login(

            "admin",

            "admin123"

        );

    }

}


64. Locators with Data-Driven Testing

Locators and Data Providers can work together. The Data Provider supplies test data while the Page Class handles element identification and interaction.

@DataProvider(name = "loginData")

public Object[][] loginData() {

    return new Object[][] {

        {"admin", "admin123"},

        {"manager", "manager123"},

        {"employee", "employee123"}

    };

}

 

@Test(dataProvider = "loginData")

public void loginTest(

    String username,

    String password) {

 

    loginPage.login(username, password);

}

The test data changes for every execution, while the locators remain centralized inside LoginPage.


65. Locators with TestNG

TestNG manages test execution while Page Classes manage Selenium page interactions.

TestNG

   |

   v

@Test Method

   |

   v

Page Class

   |

   v

Locator

   |

   v

WebDriver

   |

   v

Browser

This separation creates a cleaner automation framework.


66. Interview Questions on Locators in Page Classes

1. What is a locator?

A locator is a mechanism used by Selenium WebDriver to identify a web element on a page.

2. Why are locators placed inside Page Classes?

Locators are placed inside Page Classes to centralize element identification and separate page implementation from test logic.

3. What are common Selenium locators?

Common strategies include ID, name, className, tagName, linkText, partialLinkText, CSS selector, and XPath.

4. What is the difference between a locator and WebElement?

A locator describes how an element should be found, while WebElement represents an element obtained from the page.

5. Why should locator variables generally be private?

Private locators support encapsulation and prevent test classes from depending directly on Page Class implementation details.

6. What is @FindBy?

@FindBy is a Selenium annotation used to define WebElements using locator strategies in Page Objects.

7. What is the advantage of POM locators?

They centralize UI element definitions and make locator maintenance easier.

8. Why should absolute XPath generally be avoided?

Absolute XPath depends heavily on the exact DOM hierarchy and can break when the page structure changes.

9. When should XPath be used?

XPath is useful when text, relationships, partial attributes, or complex element conditions are required.

10. What is a CSS selector?

A CSS selector is a selector syntax used to identify HTML elements based on IDs, classes, attributes, hierarchy, and other CSS selection rules.

11. Can Page Classes use dynamic locators?

Yes. A Page Class can construct a locator dynamically based on values such as product names or user names.

12. Where should Selenium element interaction logic be placed?

Element interaction logic should generally be placed inside the relevant Page Class.

13. What happens when a locator changes?

With a well-designed POM framework, the locator can usually be updated in the corresponding Page Class without changing every test that uses the page method.

14. Can locators be used with explicit waits?

Yes. Selenium's ExpectedConditions can accept By locators for conditions such as visibility and clickability.

15. What makes a good locator?

A good locator is stable, unique, readable, maintainable, and resistant to unnecessary UI changes.


67. Quick Reference Table

ConceptPurpose
By.id()Locate by ID
By.name()Locate by name attribute
By.className()Locate by one class name
By.tagName()Locate by HTML tag
By.linkText()Locate link by exact text
By.partialLinkText()Locate link using partial text
By.cssSelector()Locate using CSS selector
By.xpath()Locate using XPath
@FindByDefine Page Object WebElements
Page ClassStores locators and page actions
WebDriverPerforms browser automation


68. Learning Roadmap for Locators in Page Classes

  1. Understand HTML elements and attributes.
  2. Learn Selenium locator strategies.
  3. Practice ID and name locators.
  4. Learn CSS selectors.
  5. Learn XPath.
  6. Understand relative XPath.
  7. Practice dynamic element locators.
  8. Learn Page Object Model.
  9. Create basic Page Classes.
  10. Move locators into Page Classes.
  11. Create reusable page methods.
  12. Learn @FindBy and PageFactory-style Page Objects.
  13. Combine locators with explicit waits.
  14. Combine Page Classes with TestNG.
  15. Combine POM with Data Providers.
  16. Build a complete reusable Selenium automation framework.


69. Practical Exercises

  1. Create a LoginPage class with username, password, and login button locators.
  2. Create a RegistrationPage with name, email, mobile, password, and submit locators.
  3. Create a SearchPage with search input and search button locators.
  4. Create a ProductPage with product and Add to Cart locators.
  5. Create a CartPage with cart and checkout locators.
  6. Practice ID, CSS, and XPath locators on the same page.
  7. Create dynamic product locators using product names.
  8. Implement explicit waits using Page Class locators.
  9. Use Page Classes with TestNG tests.
  10. Use Page Classes with a TestNG Data Provider.
  11. Create a complete POM-based Selenium framework.


70. Summary

Locators are the foundation of Selenium element interaction. They tell WebDriver how to identify the elements that need to be clicked, typed into, read, selected, or otherwise manipulated.

In a Page Object Model framework, locators should generally be maintained inside Page Classes. The Page Class combines locators with reusable methods that represent actions on the page, while the Test Class focuses on test scenarios and validations.

Stable IDs, useful data attributes, CSS selectors, and well-designed XPath expressions can all be valuable depending on the application's HTML structure. Fragile absolute XPath and unstable generated attributes should generally be avoided.

Locators become even more powerful when combined with Page Object Model, explicit waits, TestNG, Data Providers, reusable utilities, and a well-structured Selenium automation framework.


71. Course Resources

Learn more about Selenium WebDriver, locators, TestNG, Page Object Model, data-driven testing, and automation framework development through the following JustAcademy resources. The Selenium course page lists locators, TestNG, data-driven testing, POM, and automation framework development among its curriculum areas. :contentReference[oaicite:1]{index=1}

Final Takeaway: Keeping reliable locators inside Page Classes is a key part of building maintainable Selenium automation frameworks. It separates element identification from test scenarios, improves reusability, and makes UI changes easier to manage.

whatsapp