Exit course
Chapter 6 of 12 Intermediate 8 min read 2 quick checks Updated

Role-Based, Label and Relative Locators

On this page
  1. Roles and accessible names
  2. Playwright's user-facing locators
  3. Strict mode
  4. Labels in Selenium
  5. Selenium 4 relative locators
  6. Where user-facing locators fall short
  7. Summary

CSS and XPath describe markup. Users do not see markup: they see a button called "Login", a field labelled "Password", a checkbox next to "Remember me". Locators that describe the page the way a user perceives it break far less often, because the things they depend on (roles, labels, visible names) only change when the user-facing page changes, and then the test should notice.

Roles and accessible names#

Semantic HTML elements have an implicit ARIA role (<button> is a button, <a href> is a link, <input type="checkbox"> is a checkbox, <select> is a combobox, <h1> is a heading), and any element can be given one explicitly with role="...". Generic containers such as <div> and <span> have no meaningful role of their own, which is why a clickable div is invisible to role locators (more on that at the end of this chapter). Every interactive element should also have an accessible name: the button's text, the field's <label>, or an aria-label. Assistive technology such as a screen reader announces exactly these two things: "Login, button".

The Accessibility pane in Chrome DevTools shows both for the selected element. Selenium 4 can read them too, through the WebDriver commands for computed role and label (tests/test_user_facing.py):

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

LOGIN = "https://the-internet.herokuapp.com/login"
FORM = "https://www.selenium.dev/selenium/web/web-form.html"


def test_role_and_accessible_name(driver):
    driver.get(FORM)
    submit = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
    assert submit.aria_role == "button"
    assert submit.accessible_name == "Submit"
    text_input = driver.find_element(By.NAME, "my-text")
    assert text_input.accessible_name == "Text input"

Selenium has no By strategy that finds elements by role and name; aria_role and accessible_name let you assert on them once found. Playwright makes them the primary way to find things.

Playwright's user-facing locators#

The examples use a small Playwright Test project. tests/fixtures.ts adds an automatic fixture that names each TestingBot session and marks it passed or failed; it does nothing locally:

import { test as base, expect } from '@playwright/test';

function executor(action: string, args: Record<string, unknown>): string {
  return `testingbot_executor: ${JSON.stringify({ action, arguments: args })}`;
}

export const test = base.extend<{ testingbotStatus: void }>({
  testingbotStatus: [async ({ page }, use, testInfo) => {
    const remote = !!testInfo.project.use.connectOptions;
    if (remote) {
      await page.evaluate(() => {}, executor('setSessionName', { name: testInfo.title }));
    }
    await use();
    if (remote) {
      const passed = testInfo.status === testInfo.expectedStatus;
      await page.evaluate(() => {}, executor('setSessionStatus', { passed }));
    }
  }, { auto: true }],
});

export { expect };

Chapter 10 shows the config that connects to TestingBot; the Playwright tutorial explains it step by step. Now the form, filled without a single CSS selector, in tests/user-facing.spec.ts:

import { test, expect } from './fixtures';

test('fill the web form by label and role', async ({ page }) => {
  await page.goto('https://www.selenium.dev/selenium/web/web-form.html');
  await expect(page.getByRole('heading', { name: 'Web form' })).toBeVisible();

  await page.getByLabel('Text input').fill('Hello');
  await page.getByLabel('Password').fill('secret');
  await page.getByRole('combobox', { name: 'Dropdown (select)' }).selectOption('Two');
  await page.getByRole('checkbox', { name: 'Default checkbox' }).check();
  await page.getByRole('radio', { name: 'Default radio' }).check();
  await page.getByRole('button', { name: 'Submit' }).click();

  await expect(page.getByText('Received!')).toBeVisible();
});

test('log in with user-facing locators', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/login');
  await page.getByLabel('Username').fill('tomsmith');
  await page.getByLabel('Password').fill('SuperSecretPassword!');
  await page.getByRole('button', { name: 'Login' }).click();

  await expect(page.getByText('You logged into a secure area!')).toBeVisible();
  await expect(page.getByRole('link', { name: 'Logout' })).toBeVisible();
});

Remember the login button from the previous chapter, whose text sits in an <i> with a leading space? getByRole('button', { name: 'Login' }) finds it without any of the text() versus normalize-space() care, because the accessible name is computed the way a browser computes it for a screen reader. By default the name match is case-insensitive and matches a substring; add exact: true to require the whole name.

The full set of built-in locators, roughly in the order to try them:

Locator Use for
getByRole(role, { name }) buttons, links, checkboxes, headings, rows, cells: almost everything interactive
getByLabel(text) form fields with a <label> or aria-label
getByPlaceholder(text) fields that only have a placeholder
getByText(text) non-interactive text, such as messages
getByAltText(text) / getByTitle(text) images, elements with a title
getByTestId(id) elements with no stable user-facing handle (next chapter)

A designer replaces the text button "Delete" with a trash-can icon and no text. getByRole('button', { name: 'Delete' }) starts failing. What is the best fix?

The failing locator found a real accessibility regression: an icon-only button with no accessible name is announced as just "button". Restoring the name fixes users and test at once. The icon selector couples the test to an SVG class, and the position couples it to the toolbar layout.

Strict mode#

A Playwright locator that matches several elements is fine for counting and for nth(), but an action on it fails instead of picking the first one:

test('strict mode refuses an ambiguous locator', async ({ page }) => {
  await page.goto('https://www.selenium.dev/selenium/web/web-form.html');
  await expect(page.getByRole('checkbox')).toHaveCount(2);
  const error = await page.getByRole('checkbox').check({ timeout: 2000 }).catch((e: Error) => e);
  expect(String(error)).toContain('strict mode violation');
});

This is a feature: Selenium's find_element would silently click the first checkbox, and you would find out later that the test checked the wrong one. In Playwright, an ambiguous locator fails loudly, with the list of matches in the error.

Labels in Selenium#

Selenium has no getByLabel, but the web form wraps each input in its label, so XPath expresses it directly:

def test_find_by_visible_label(driver):
    driver.get(FORM)
    field = driver.find_element(
        By.XPATH, "//label[normalize-space(text())='Text input']//input")
    field.send_keys("hello")
    assert field.get_attribute("value") == "hello"

normalize-space(text()) uses only the label's own text ("Text input"), not the text of everything inside it. When the label is separate and linked with for="username", the for value is the input's id, and By.ID is simpler. Small helpers like by_label(driver, "Text input") in a page object or a shared module make this read as well as Playwright's version.

Selenium 4 relative locators#

Selenium 4 added relative locators: find an element by where it appears on screen relative to another one, with above, below, to_left_of, to_right_of and near:

def test_relative_locator(driver):
    driver.get(LOGIN)
    password = driver.find_element(
        locate_with(By.TAG_NAME, "input").below({By.ID: "username"}))
    assert password.get_attribute("id") == "password"

Relative locators use the rendered position of elements (their bounding boxes), not the DOM structure. That makes them useful for one specific job: a field that has no usable attributes at all, next to a label or element that does. It also makes them sensitive to layout: a responsive breakpoint that puts two fields side by side turns below into to_right_of. Treat them as a last resort before positional selectors, not as a first choice. Our Selenium 4 documentation has examples in other languages.

A test using locate_with(By.TAG_NAME, "input").below({By.ID: "email"}) passes on desktop and fails on a narrow mobile viewport. What is the most likely reason?

The DOM is usually identical across viewports; the CSS layout is not. Relative locators compare bounding boxes, so a field that is below on desktop can be beside or above on mobile.

Where user-facing locators fall short#

  • Translated or frequently edited copy. If the app runs in five languages, getByRole('button', { name: 'Save' }) needs the name per locale. Either run the tests in one locale or use test ids.
  • Repeated names. Ten "Edit" links in a table all have the same name; scope to the row first (chapter 8).
  • Missing semantics. A div with a click handler has no role and no name. That is an accessibility bug worth fixing; until it is, a test id is the honest workaround. The accessibility testing course covers how to catch these automatically.

Summary#

  • Roles and accessible names describe what users perceive, so they break only when users would notice.
  • In Playwright, start with getByRole and getByLabel; strict mode catches ambiguous locators.
  • In Selenium, assert on aria_role and accessible_name, and use label-based XPath in a helper.
  • Relative locators depend on rendered layout: useful for attribute-less fields, fragile across viewports.