Skip to content
Velloreth
Programming 5 min read

Playwright Locators: Find Buttons Without Brittle CSS

Use Playwright role and label locators, understand strict matches and auto-waiting, and test a small form without fixed sleeps or fragile selectors.

By

A browser test should fail when the user-facing behavior breaks, not whenever a designer renames a CSS class. Playwright locators help express that intent: find the button a person can identify, fill the field with a visible label, and wait for the result that matters.

This guide uses a tiny form loaded directly into a test page. It avoids accounts, remote services, and unpredictable network data so the locator behavior stays easy to inspect. You can later apply the same ideas to a local application.

Why this is a current practical topic

Playwright appears in the testing-tool usage table of the 2026 Stack Overflow survey. That is a reason to consider learning it, not evidence that every project needs a browser test suite. The official locator guide recommends prioritizing user-facing attributes and explicit testing contracts.

Read the site’s end-to-end testing guide for the wider testing strategy. This article covers a smaller problem: how the test identifies the right element after deciding that browser-level coverage is worthwhile.

Set up a disposable test folder

Use a Node version supported by your installed Playwright release. In an empty project, initialize npm if needed, then install the test runner and its Chromium browser:

npm init -y
npm install -D @playwright/test
npx playwright install chromium

Browser installation downloads files and uses disk space. On a managed machine, follow the approved installation route. A real project should keep its dependency lockfile and use its existing test configuration rather than mixing two runners unintentionally.

Create tests/reading.spec.js. The default Playwright test command can discover this conventional test filename. The fixture in the next section creates its own document; no development server is required for this exercise.

Write the smallest meaningful interaction

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

test('adds a reading title', async ({ page }) => {
  await page.setContent(`
    <label for="title">Reading title</label>
    <input id="title">
    <button type="button">Add reading</button>
    <p role="status"></p>
    <script>
      document.querySelector('button').addEventListener('click', () => {
        document.querySelector('[role="status"]').textContent =
          document.querySelector('input').value;
      });
    </script>
  `);

  await page.getByLabel('Reading title').fill('One chapter');
  await page.getByRole('button', { name: 'Add reading', exact: true }).click();
  await expect(page.getByRole('status')).toHaveText('One chapter');
});

Run:

npx playwright test

A bare minimal project uses the default browser configuration. In a scaffolded project that defines named browser projects, you can select one with --project=chromium. That flag selects a configured project; it does not create one.

The form’s script uses ordinary DOM selectors to implement the tiny demo. The test uses labels and roles because it describes how someone interacts with that implementation. Those two purposes do not need identical selectors.

Understand what each locator says

getByLabel('Reading title') connects the test to the form’s accessible label. The explicit for and matching id establish that relationship. A placeholder can be a hint, but it is not a reason to omit a real label.

getByRole('button', { name: 'Add reading' }) identifies both the type of control and its accessible name. A native button already has a button role. You do not need to add a redundant role attribute merely to make the test work.

getByRole('status') identifies the result region. The assertion waits for its text to match the intended outcome. That is more meaningful than checking that the button was clicked or that a fixed number of milliseconds elapsed.

The site’s form accessibility guide explains why the same labels benefit readers using assistive technology. Test-friendly semantics and usable controls often support each other, but one passing locator does not prove that the entire interaction is accessible.

Avoid the common brittle shortcuts

A selector such as .blue-button:nth-child(3) describes appearance and position. Either can change while the behavior stays correct. A readable role-and-name locator makes the intent more obvious to a reviewer.

When several matching buttons exist, narrow the scope to the correct section or use a more specific accessible name. Do not add .first() reflexively. Selecting the first match can hide a duplicate-control bug and make the test act on an unintended element.

A test identifier is reasonable when user-facing attributes cannot express a stable contract. Agree on it deliberately. If the behavior under test is the visible label, however, a test identifier alone can miss a regression in that label.

Wait for state, not a guessed duration

Playwright locators support auto-waiting for actions, and its web assertions retry while waiting for the expected result. Avoid a sleep before every click. A short sleep can be too short on a slow machine and needlessly slow on a fast one.

That does not mean all waiting disappears. A test still needs a meaningful completion condition. For a real submission, it might be a visible confirmation or updated record. The flaky-test guide discusses why uncontrolled data and ambiguous readiness often matter more than simply increasing a timeout.

Check the test itself

Temporarily change the expected title and confirm the test fails for the intended reason. Then restore it. A test that never fails when the behavior changes may be checking the wrong element or never reaching its assertion.

Inspect the visible page when adapting this example to a real app. Readability, focus order, and responsive layout cannot be inferred from successful selectors alone. Keep the test focused and add broader browser coverage only when the product’s audience and risk justify it.

Diagnose a duplicate match carefully

If a click reports more than one matching element, inspect the page rather than immediately choosing an index. Two buttons with the same name may be intentional, such as one in a header and one in a card, or they may expose an accidentally duplicated component. Scope the locator to a named section only when that section is part of the intended user journey.

For localized applications, remember that user-facing labels can change with language. Run the test under a known locale and make that assumption explicit. A stable test ID can support a different contract, but it should not accidentally remove coverage for important text. Choose the locator based on what the test promises to verify, not whichever selector happens to make the current failure disappear.

Sources and limits

Checked October 26, 2026 against Playwright’s locator guide, its installation guide and the 2026 Stack Overflow technology data. The tutorial demonstrates locator intent, not full accessibility certification or proof of every browser’s behavior.

Frequently asked questions

What is a locator?
It is a reusable way to find an element when Playwright performs an action or assertion.
Why not use a CSS class?
CSS is useful when needed, but styling classes often change without changing the user-visible behavior.
Should I add a sleep before every click?
No. Use locators and retrying assertions for the intended state rather than arbitrary delays.
Are role locators a complete accessibility test?
No. They can expose some naming and semantic problems, but a wider audit is still needed.