Locators

What is a Locator in Playwright

What is a Locator in Playwright: definition, detailed explanation, practical usage, examples, mistakes, interview notes, and practice for Playwright automation.

Definition and Brief Explanation

Definition: A Playwright Locator is a reusable query that finds elements when an action or assertion runs.

Explanation: A Locator is not a stored DOM element. Playwright re-evaluates it at the moment of use, which helps tests survive re-rendering, loading changes, and dynamic UI updates. Good Locators are readable, stable, and close to how a user understands the page.

Why It Matters

  • It makes tests easier to read because the Locator describes the target element clearly.
  • It reduces flaky failures caused by layout changes or generated CSS classes.
  • It works with Playwright auto-waiting, so actions and assertions wait for the element state.
  • It supports maintainable Page Object Model code because selectors are meaningful.

How It Works

  1. Identify the element by user-facing meaning first: role, label, text, placeholder, alt text, or title.
  2. Confirm the Locator points to the intended element and is unique when used for an action.
  3. Use filters, chaining, or test ids when the page has repeated controls.
  4. Avoid positional Locators unless order is the behavior being tested.

Syntax and Examples

Example 1: Role Locator for a button

await page.getByRole('button', { name: 'Login' }).click();

Explanation: This targets the Login button by its accessible role and name. If another text node says Login but is not a button, this Locator will not accidentally click it.

Example 2: Label Locator for a form input

await page.getByLabel('Email').fill('qa@example.com');

Explanation: This finds the input connected to the Email label. It reads like a user instruction and stays stable when layout or CSS changes.

Example 3: Filtering a repeated card

const product = page.getByRole('article').filter({ hasText: 'Wireless Mouse' });
await product.getByRole('button', { name: 'Add to cart' }).click();

Explanation: The first Locator narrows to the correct product card. The chained button Locator then clicks Add to cart only inside that card.

Common Mistakes

  • Using generated CSS classes as the first option.
  • Using broad text that appears in many places.
  • Adding nth() only to silence strict mode.
  • Storing element handles instead of using Locators.

Interview Notes

  1. What does Locator mean in Playwright?
  2. When would you choose Locator?
  3. How do you make the Locator unique?
  4. What makes this Locator stable or unstable?

Practice Task

Create a small Playwright example for Locator. Add one positive assertion, one note about what can go wrong, and one improvement that would make the test more maintainable.