QA Interview Hub · Knowledge base · Quizzes · Українська

Selenium + Java › Locators and waits

Locators: By, CSS versus XPath, relative locators

A locator is chosen for resilience, not speed: a dedicated data-testid attribute is best, then CSS, with XPath for text and moving to an ancestor. The speed difference between CSS and XPath is unnoticeable. Absolute XPaths, indexes and generated classes break with the first markup change. Selenium 4 relative locators are a fallback.

Selenium · Locators

A test green on Friday cannot find a button on Monday. A developer only added a div. What went wrong?

A developer wrapped the login form in an extra div for styling, and half of the tests written with absolute XPaths stopped finding elements. The functionality did not change, but the suite is red. A locator is a contract between the test and the page, and the more it depends on accidental details (node order, generated classes), the more often the contract is broken. The lesson covers choosing a search strategy, comparing CSS and XPath, and Selenium 4 relative locators.

How it works and why. The driver.findElement(By...) method sends the driver a "strategy and value" pair, and the driver searches the current document. There are eight strategies: id, name, className (a single class only, compound names are not supported), tagName, linkText, partialLinkText, cssSelector and xpath. All but the last two are fast shortcuts for typical cases, while CSS and XPath cover the rest. Behaviour on failure differs: findElement throws NoSuchElementException, while findElements returns an empty list.

// findElement throws NoSuchElementException when nothing matches
// findElements returns an empty list: handy for "is absent"
boolean gone = driver.findElements(By.id("spinner")).isEmpty();

Choose by resilience to change, not by speed: in modern browsers the difference between CSS and XPath is invisible next to network and rendering. A practical order:

The locator choice ladder

1. data-testid or a stable ida contract, independent of layout2. Meaningful CSS: role, name, structuresurvives style changes3. XPath by text or ancestorwhen CSS cannot reach4. Absolute paths, generated classesbreaks on any edit
Figure 1. Climb as high as you can. Rungs 1-2 live for years, rung 4 breaks on the first layout edit.
CSSXPath
Readabilityshorter, familiar to front-end developerswordier
Search by textnoyes: //button[normalize-space()='Log in']
Moving to a parent or ancestor:has() selects a parent by a descendantyes: .., ancestor::
Speedthe difference is negligiblethe same

Example: from fragile to resilient. Two locators that break:

// breaks on any wrapper or new block
driver.findElement(By.xpath("/html/body/div[3]/div[2]/form/button[1]"))
    .click();
// a generated class changes with every build
driver.findElement(By.cssSelector(".css-1x2y3z")).click();

The first is tied to a position in the tree, so an extra wrapper shifts the path. The second uses a class generated by a CSS-in-JS library: it changes with the next build. The fix is not a "smarter" selector but an agreement: ask developers to add data-testid on the elements tests work with. When there is no such attribute, take the most stable thing available (id, name, a role, a label):

// a contract with developers: a dedicated test attribute
driver.findElement(By.cssSelector("[data-testid='login-submit']"))
    .click();

// a table row by its content: CSS is not enough, use XPath
driver.findElement(By.xpath(
    "//tr[td[normalize-space()='Ivan']]//button[@title='Delete']"))
    .click();

XPath in the second example is justified: the row must be found by its content and then the button inside it, which CSS cannot do. Relying on text that is translated or edited by marketing is also fragile, so for multilingual interfaces text locators are better replaced with an attribute.

Relative locators and combinations. Selenium 4 added search by position relative to another element: above, below, toLeftOf, toRightOf and near (by default elements within 50 pixels).

import static org.openqa.selenium.support.locators.RelativeLocator.with;

WebElement password = driver.findElement(
    with(By.tagName("input")).below(By.id("email")));

WebElement cancel = driver.findElement(
    with(By.tagName("button")).toLeftOf(By.id("save")));

This is a fallback for elements without reliable attributes, for example a field without an id under a label. Layout changes more often than an attribute and depends on window size, so a relative locator is more fragile than data-testid. For combining there are ByAll (any of the locators) and ByChained (search inside the previous result), both from the org.openqa.selenium.support.pagefactory package:

// будь-який із локаторів / any of the locators
new ByAll(By.id("password-field"), By.id("pwd"));
// пошук всередині результату попереднього / inside the previous result
new ByChained(By.id("login-form"), By.tagName("input"));

Elements inside a shadow DOM are not seen by an ordinary search: take element.getShadowRoot() and search inside that root. Content of an iframe needs a context switch (the lesson “BiDi instead of CDP, Actions, files, iframes and windows”).

Limits and alternatives. A locator finds an element in the DOM but says nothing about whether it can be clicked: it may be hidden, covered or not ready yet (waits are in the lesson “Waits: implicit, explicit, fluent”). Playwright has role and label locators (getByRole, getByLabel) that push towards accessible markup; in Selenium such lookups have to be built by hand through CSS attributes, so the data-testid agreement is especially useful here. Locators hidden in a Page Object (the lesson “Page Object Model: what it is and the rules”) only need changing in one place.

Common mistakes.

  • Copying XPath from DevTools ("Copy full XPath"): you get an absolute path that breaks on the first layout change.
  • Using indexes (li[3]) when the order varies: the test clicks the wrong element and passes while checking the wrong thing.
  • Using By.className("btn btn-primary"): compound class names are not supported, you need CSS .btn.btn-primary.
  • Checking absence with findElement in try/catch: findElements(...).isEmpty() is shorter and more honest.
  • Relying on relative locators in responsive layouts: on a narrower screen elements swap places.

Check yourself

The locator By.className("form-control input-lg") throws an exception. What is the cause and how do you write the same thing?

Answer

By.className takes a single class, and a space in the value makes it compound, which is not supported. Use the CSS selector .form-control.input-lg, which requires both classes at once.

You need to press "Delete" in the table row whose first cell says "Ivan". Which locator, and why is CSS not enough?

Answer

XPath: //tr[td[normalize-space()='Ivan']]//button[@title='Delete']. CSS cannot select by a cell's text, and :has() does not filter by text content. If the row has a data attribute with an identifier, CSS using it would be more resilient.

In an interview. Junior: I find an element through findElement(By...). I prefer id or data-testid and use CSS and XPath when they are missing. For absence I use findElements. Middle/Senior: I choose a locator by resilience, not speed: a dedicated test attribute agreed with developers, then CSS, XPath only for text and moving to an ancestor. I treat relative locators and absolute paths as a fallback and hide all locators in a Page Object so they are fixed in one place.

More articles in this chapter