Playwright CSS Locators

A house address uses a street name and number to guide a visitor to the exact door. CSS locators guide Playwright the same way, using the same address system web designers already use to style pages.

Why CSS Locators Feel Familiar

Anyone who has written a little HTML or CSS already understands the symbols CSS locators use. This overlap makes CSS locators one of the easiest locator types for a beginner to pick up quickly.

A Sample Login Form

<div class="login-box">
  <input id="username" type="text">
  <input id="password" type="password">
  <button class="submit-btn">Login</button>
</div>

Targeting by ID

page.locator('#username');

A hash symbol targets an element's ID. IDs should stay unique on a page, making this one of the most reliable locator patterns available.

Targeting by Class

page.locator('.submit-btn');

A dot symbol targets a class name. Classes can repeat across many elements, so this pattern sometimes matches more than one element at once.

Targeting by Tag Name

page.locator('button');

This matches every button on the entire page, which rarely works alone on a busy page with multiple buttons.

Combining Selectors for Precision

page.locator('div.login-box input#username');

This line narrows the search step by step: first find the div with class "login-box," then find the input with ID "username" inside it. Combining selectors avoids accidentally matching an unrelated element elsewhere on the page.

A Complete Login Example

await page.locator('#username').fill('john_doe');
await page.locator('#password').fill('mypassword123');
await page.locator('.submit-btn').click();

These three lines fill both fields and submit the form, mirroring exactly what a real visitor does when logging in.

Attribute Selectors

page.locator('input[type="email"]');
page.locator('[data-testid="login-button"]');

Attribute selectors target elements based on any HTML attribute, not only ID or class. Many teams add a custom data-testid attribute specifically to give tests a stable, dedicated hook.

When CSS Locators Struggle

A page with no IDs and only auto-generated class names, such as "css-a3f9x," makes CSS locators fragile. These class names often change every time a developer rebuilds the website.

Quick Practice Task

Visit any webpage, inspect three different elements, and write a CSS locator for each one using ID, class, and attribute selectors.

Key Takeaways

  • CSS locators use IDs, classes, tags, and attributes to find elements.
  • ID-based locators tend to stay the most stable over time.
  • Combining selectors narrows results down to one exact element.
  • A dedicated data-testid attribute protects tests from design changes.

Leave a Comment

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