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
- Identify the element by user-facing meaning first: role, label, text, placeholder, alt text, or title.
- Confirm the Locator points to the intended element and is unique when used for an action.
- Use filters, chaining, or test ids when the page has repeated controls.
- 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
- What does Locator mean in Playwright?
- When would you choose Locator?
- How do you make the Locator unique?
- 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.