---
title: Role-Based, Label and Relative Locators | TestingBot
description: 'CSS and XPath describe markup. Users do not see markup: they see a button
  called &quot;Login&quot;, a field labelled &quot;Password&quot;, a checkbox next
  to…'
source_url:
  html: https://testingbot.com/resources/courses/locator-strategies/role-based-and-relative-locators
  md: https://testingbot.com/resources/courses/locator-strategies/role-based-and-relative-locators.md
---

Course

[Selenium Locators and Locator Strategies](https://testingbot.com/resources/courses/locator-strategies)

Chapter 6 of 12

1. [1 Selenium Locators: Strategies That Survive Change](https://testingbot.com/resources/courses/locator-strategies)
2. [2 Why Tests Break on Locators](https://testingbot.com/resources/courses/locator-strategies/why-locators-break)
3. [3 Inspect the DOM and Test Selectors in DevTools](https://testingbot.com/resources/courses/locator-strategies/inspect-and-test-selectors-in-devtools)
4. [4 CSS Selectors for Test Automation](https://testingbot.com/resources/courses/locator-strategies/css-selectors)
5. [5 XPath in Selenium: Text, Axes and When to Use It](https://testingbot.com/resources/courses/locator-strategies/xpath-in-selenium)
6. [6 Role-Based, Label and Relative Locators](https://testingbot.com/resources/courses/locator-strategies/role-based-and-relative-locators)
7. [7 A Test ID Contract With Your Developers](https://testingbot.com/resources/courses/locator-strategies/a-test-id-contract)
8. [8 Shadow DOM and iframes](https://testingbot.com/resources/courses/locator-strategies/shadow-dom-and-iframes)
9. [9 Lists, Tables and Dynamic Content](https://testingbot.com/resources/courses/locator-strategies/lists-tables-and-dynamic-content)
10. [10 A Note on Mobile Locators](https://testingbot.com/resources/courses/locator-strategies/a-note-on-mobile-locators)
11. [11 A Locator Review Checklist](https://testingbot.com/resources/courses/locator-strategies/locator-review-checklist)
12. [12 Locator Strategies Knowledge Check](https://testingbot.com/resources/courses/locator-strategies/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 6 of 12 Intermediate 8 min read 2 quick checks Updated Nov 2026 

# Role-Based, Label and Relative Locators
On this page
1. [Roles and accessible names](https://testingbot.com#roles-and-accessible-names)
2. [Playwright's user-facing locators](https://testingbot.com#playwright-s-user-facing-locators)
3. [Strict mode](https://testingbot.com#strict-mode)
4. [Labels in Selenium](https://testingbot.com#labels-in-selenium)
5. [Selenium 4 relative locators](https://testingbot.com#selenium-4-relative-locators)
6. [Where user-facing locators fall short](https://testingbot.com#where-user-facing-locators-fall-short)
7. [Summary](https://testingbot.com#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[#](https://testingbot.com#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`):

```python
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[#](https://testingbot.com#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:

```typescript
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](https://testingbot.com/resources/courses/playwright/run-on-a-cloud-grid) explains it step by step. Now the form, filled without a single CSS selector, in `tests/user-facing.spec.ts`:

```typescript
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?

 Ask for `aria-label="Delete"` on the button: screen reader users have lost the name too, and the locator works again Switch to `locator('button svg.icon-trash')` Switch to `getByRole('button').nth(4)`

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[#](https://testingbot.com#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:

```typescript
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[#](https://testingbot.com#labels-in-selenium)

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

```python
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[#](https://testingbot.com#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`:

```python
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](https://testingbot.com/support/web-automate/selenium/selenium4#relative-locators) 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?

 Relative locators are not supported in mobile browsers The DOM is different on mobile Relative locators use rendered positions, and the responsive layout moved the field `By.TAG_NAME` is case-sensitive on mobile

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[#](https://testingbot.com#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](https://testingbot.com/resources/courses/accessibility-testing) covers how to catch these automatically.

## Summary[#](https://testingbot.com#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.

[Previous · Chapter 5 XPath in Selenium: Text, Axes and When to Use It](https://testingbot.com/resources/courses/locator-strategies/xpath-in-selenium) [Next · Chapter 7 A Test ID Contract With Your Developers](https://testingbot.com/resources/courses/locator-strategies/a-test-id-contract)

On this page

1. [Roles and accessible names](https://testingbot.com#roles-and-accessible-names)
2. [Playwright's user-facing locators](https://testingbot.com#playwright-s-user-facing-locators)
3. [Strict mode](https://testingbot.com#strict-mode)
4. [Labels in Selenium](https://testingbot.com#labels-in-selenium)
5. [Selenium 4 relative locators](https://testingbot.com#selenium-4-relative-locators)
6. [Where user-facing locators fall short](https://testingbot.com#where-user-facing-locators-fall-short)
7. [Summary](https://testingbot.com#summary)

Certification

Earn the free, resume-worthy TestingBot Locator Strategies Certification for this course.

[How it works](https://testingbot.com/resources/courses/locator-strategies/certification)
