Playwright Locators

A librarian never says "bring me a book." A librarian says "bring me the blue book on the third shelf, second row." Playwright needs the same precise instructions to find one exact element among hundreds on a webpage, and a locator provides that precision.

What a Locator Really Does

A webpage often contains dozens of buttons, links, and input fields. A locator is a set of instructions telling Playwright exactly which one of those elements to work with. Without a correct locator, Playwright has no way of knowing which button a test actually means.

Finding One Element Among Many

Webpage
  |-- Logo
  |-- Navigation Menu
  |-- Search Box        <-- Locator points here
  |-- Product Grid
  |-- Footer Links

The locator ignores the logo, menu, and footer completely. It zooms directly into the search box because the test only cares about that element.

Creating a Basic Locator

const searchBox = page.locator('#search-input');

This line does not search the page immediately. It creates a description of where to look, similar to writing an address on an envelope before mailing it.

Using the Locator to Act

await searchBox.fill('wireless headphones');
await searchBox.press('Enter');

The moment an action runs, Playwright finally searches the page using that description, finds the matching element, and performs the action on it.

Role-Based Locators: The Recommended Approach

Playwright recommends finding elements the way a real user sees them, such as by their visible label or role.

await page.getByRole('button', { name: 'Add to Cart' }).click();
await page.getByLabel('Email Address').fill('user@example.com');
await page.getByPlaceholder('Search products').fill('shoes');

These locators read almost like plain English, describing exactly what a person would see and click.

A Real-World Example

An online store test needs to click "Add to Cart" on a specific product. Using the visible button text keeps the test readable and resistant to changes in the website's underlying code structure.

Why Locators Matter So Much

A wrong or fragile locator breaks a test even when the actual website works perfectly fine. A well-chosen locator keeps a test stable for months, surviving small design updates without any changes needed.

Quick Practice Task

Open any website, right-click a button, and inspect its HTML. Write down three possible ways to locate that button, then decide which option looks the most stable.

Key Takeaways

  • A locator describes exactly which element Playwright should find.
  • Creating a locator does not search the page until an action runs.
  • Role-based locators mimic how a real user identifies elements.
  • Stable locators keep tests working even as a website evolves.

Leave a Comment

Your email address will not be published. Required fields are marked *