Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 35 ยท Finding Elements

Choosing Stable Locators

Pick Selenium locators that survive redesigns: test ids, ARIA attributes, link text, relative locators, and a ranking that tells you which strategy to try first.

You now know how to find an element with an id, a CSS selector or an XPath expression. The next question is the one that decides whether your test suite is pleasant or miserable a year from now: which locator should you write? Almost every page offers several ways to reach the same button, and they do not age equally well. A locator that works today can break next week because a designer wrapped a div around a form.

A stable locator keeps working while the page changes in ways that do not matter to a user: new styling, a reordered layout, extra wrapper elements, a translated heading. A brittle locator is welded to details of the page's current structure, so any such change breaks it. This lesson gives you a way to tell them apart and a ranking to follow.

Selenium itself (the browser, the driver and your test code) cannot run on this site. The Selenium calls below are read-only, and the runnable examples are plain JavaScript stand-ins that score locators and simulate relative positions, so you can see the reasoning without a browser.

What makes a locator brittle

Look at two ways to click the same "Save" button:

Python
# Brittle: depends on four levels of nesting and the position of the button
driver.find_element(By.XPATH, "/html/body/div[2]/div/form/div[3]/button[1]")

# Stable: depends on one thing that exists to identify the button
driver.find_element(By.CSS_SELECTOR, '[data-testid="save-profile"]')

The first expression breaks if anyone adds a banner above the form, inserts a field, or swaps two buttons. It also tells the next reader nothing about what is being clicked. The second survives all of those changes, because the attribute was added for exactly one purpose: to name this element.

Typical sources of brittleness:

  • Absolute XPath and long parent-child chains (div > div > ul > li:nth-child(3) > a).
  • Positional indexes, such as [3] or :nth-child(2), which silently point at a different element when the list changes.
  • Generated class names like css-1x7k2q or btn-3fa9, produced by CSS-in-JS tools and build steps, which change on every build.
  • Styling classes such as btn-primary or mt-4. They describe looks, and looks change in redesigns.
  • Visible text that marketing owns, for example //button[text()='Sign up now!'] when the copy is revised each quarter.

Brittle or stable?

Brittle Absolute paths, indexes, generated classes.
Fragile Styling classes and marketing copy.
Stable Test ids, ARIA attributes, real ids.

Ask: would a user notice this change? If not, the locator should not break.

1 / 2

Test ids: the most stable choice

The most reliable locator is an attribute that exists only so tests can find the element. The convention is a data- attribute:

HTML
<button type="submit" class="btn btn-primary" data-testid="save-profile">Save</button>

Selenium has no built-in By.TEST_ID, so you use a CSS attribute selector:

Python
save = driver.find_element(By.CSS_SELECTOR, '[data-testid="save-profile"]')

The attribute name is a team convention: data-testid, data-test, data-qa and data-cy are all common. Pick one and stick to it. The trade-off is that someone has to add these attributes. If you work with the developers, ask for them. If you cannot change the page, fall back to the next options in the ranking. A small helper keeps the convention in one place:

Python
def by_test_id(value):
    return (By.CSS_SELECTOR, f'[data-testid="{value}"]')

driver.find_element(*by_test_id("save-profile"))

Ids, names and accessibility attributes

A real id is the next best thing, as long as it is meaningful and hand-written (id="email"), not generated (id="input-8f2a91"). Form controls also have name, which tends to be stable because the server depends on it.

The page's accessibility attributes are a good source too, because they describe what an element means to a user and are rarely changed in redesigns:

Python
driver.find_element(By.CSS_SELECTOR, '[aria-label="Close dialog"]')
driver.find_element(By.CSS_SELECTOR, 'button[role="tab"][aria-selected="true"]')
driver.find_element(By.CSS_SELECTOR, 'nav[aria-label="Main"] a[href="/pricing"]')

Selenium has no By.ROLE. Recent Selenium 4 releases do expose each element's computed ARIA role and accessible name as properties (element.aria_role and element.accessible_name in Python), which are handy for assertions such as "this button is called Close dialog". For finding elements, attribute selectors are the dependable route. If you can work with the accessibility attributes, you also nudge the product toward being usable with screen readers.

For links, By.LINK_TEXT and By.PARTIAL_LINK_TEXT read well and need no markup knowledge:

Python
driver.find_element(By.LINK_TEXT, "Privacy policy")
driver.find_element(By.PARTIAL_LINK_TEXT, "Privacy")

They match the visible text, so they inherit the weakness of text: a copy change or a translation breaks them. They are a good choice for stable, legally required or structural links (privacy policy, log out) and a poor one for marketing wording. Only <a> elements can be found this way.

Relative locators

Selenium 4 added relative locators: you describe an element by where it sits compared with other elements. Methods are above, below, to_left_of, to_right_of and near. In Python:

Python
from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import locate_with

password = driver.find_element(By.ID, "password")
username_field = driver.find_element(locate_with(By.TAG_NAME, "input").above(password))

near matches elements within 50 pixels of the anchor by default, and you can pass a different distance. You can chain several conditions, and the anchor can be an element or a plain locator dictionary such as {By.ID: "password"}. Java has the same idea in RelativeLocator.with(By.tagName("input")).above(By.id("password")).

Relative locators shine when elements have no good identifiers but sit in a predictable arrangement, such as a label next to an unlabeled input. Their weakness is layout: a responsive page rearranges itself at different window widths, and "below" on a desktop can become "to the right" on a tablet. Use them as a last resort and fix the window size when you do.

The next TryIt models how relative locators choose among candidates. It is a simplified stand-in (the real implementation measures live rectangles in the browser), but it shows the idea: filter by direction, then prefer the closest element.

JS A toy relative locator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that "above the password field" returned only username, and that widening near from 50 to 120 pixels pulled in more candidates. When several elements match, the nearest ones are preferred, which is what this stand-in imitates by sorting on distance.

A ranking you can use

When you stand in front of a new page, walk down this list and stop at the first option that is available and unique:

  1. A test id ([data-testid="..."]) added for tests.
  2. A meaningful, hand-written id or form name.
  3. ARIA and role attributes, or a stable href or type combined with a tag.
  4. A short CSS selector of one or two meaningful hops (form#login button[type="submit"]).
  5. Link text for stable, structural links.
  6. A relative locator when only the layout identifies the element.
  7. XPath when you need text matching or upward navigation that CSS cannot do (see XPath Locators).

Never reach for absolute XPath or generated class names. The scorer below turns that advice into code. The weights are an opinion, not a standard, but writing them down makes the ranking concrete and is a nice code-review aid.

JS Scoring locators for stability

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The test id lands on top, the absolute XPath and the generated-class selector fall to the bottom, and the same "short and meaningful" CSS selector scores well above its positional cousin. The real work, of course, is making that judgment while you write the test.

Making locators last

A few habits matter more than any single locator:

  • Keep locators in one place. Put them in page objects (see The Page Object Model) so a change means one edit, not fifty.
  • Check uniqueness. A locator that matches three elements will quietly click the first one. In the browser's DevTools console, document.querySelectorAll('[data-testid="save-profile"]').length should print 1.
  • Locate the nearest meaningful ancestor first. Find a container by test id, then search inside it: dialog.find_element(...). This turns a global search into a scoped one and removes most ambiguity.
  • Talk to developers. Ten minutes spent asking for test ids saves hours of repair work.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which locator is the most likely to survive a visual redesign?

    A dedicated test id exists only to identify the element, so layout, styling and wrapper changes do not affect it. The other options depend on structure, styling classes or position.
  2. 2. Why are generated class names such as css-1x7k2q poor locators?

    CSS-in-JS tools and build steps generate these names from hashes. The page looks identical, but the name changes, and so the test fails.
  3. 3. A relative locator such as locate_with(By.TAG_NAME, "input").above(password) depends mainly on what?

    Relative locators compare the rendered positions of elements, so a responsive layout that moves things around can change the result.
  4. 4. Selenium has no By.ROLE or By.TEST_ID. How do you locate an element by a test id?

    A CSS attribute selector passed to By.CSS_SELECTOR works with any attribute, so a small helper function can wrap the convention.

Summary

  • A stable locator survives changes a user would not notice; brittle ones depend on structure, position, generated names or styling.
  • Prefer, in order: test ids, meaningful ids or names, ARIA and role attributes, short CSS, link text for stable links, relative locators, then XPath for what CSS cannot express.
  • Selenium has no built-in test-id or role locator: use CSS attribute selectors, ideally behind one helper function.
  • Relative locators (above, below, to_left_of, to_right_of, near) describe elements by position and are sensitive to layout.
  • Keep locators in page objects, check they match exactly one element, and search inside a located container.

Next, start driving the page with Clicking and Typing.