Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS MATH

Playwright Locators


Share

Playwright Locators

A locator is a way to find an element on the page.

You create a locator first, and then you act on it or check it:

Example

const button = page.getByRole('button', { name: 'Add' });
await button.click();

A locator does not search the page when you create it.

Playwright looks for the element every time you use the locator, so it always finds the element as it is right now, even if the page has changed.


Built-in Locators

Playwright has built-in locators that find elements the way a user sees them: by role, text and label.

Use them in this order of priority:

LocatorFinds elements byExample
getByRole()Role and accessible name (button, link, heading, checkbox...)page.getByRole('button', { name: 'Log in' })
getByText()Text contentpage.getByText('Welcome, student!')
getByLabel()The text of the form labelpage.getByLabel('Username')
getByPlaceholder()The placeholder of an inputpage.getByPlaceholder('Enter your password')
getByAltText()The alt text of an imagepage.getByAltText('Green circle')
getByTitle()The title attributepage.getByTitle('Notes saved today')
getByTestId()The data-testid attributepage.getByTestId('welcome')

The role is the type of the element, like button, link or heading.

The accessible name is the name of the element for screen readers, usually its text or its label.

A screen reader is a program that reads the page aloud for people who cannot see it.

getByRole() is the best choice for most elements.

It finds elements the same way screen readers do, so your tests also check that the page is accessible.

Use getByTestId() when nothing else works, for example for a text that changes.

This test logs in to the practice login page with built-in locators:

Example

tests/builtins.spec.js

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

test('log in with built-in locators', async ({ page }) => {
  await page.goto('https://www.w3schools.com/playwright/practice/login.html');
  await expect(page.getByRole('heading', { name: 'Log in' })).toBeVisible();
  await page.getByLabel('Username').fill('student');
  await page.getByPlaceholder('Enter your password').fill('w3schools');
  await page.getByRole('button', { name: 'Log in' }).click();
  await expect(page.getByText('Welcome, student!')).toBeVisible();
  await expect(page.getByTestId('welcome')).toHaveText('Welcome, student!');
});

test('find by alt text and title', async ({ page }) => {
  await page.goto('https://www.w3schools.com/playwright/practice/actions.html');
  await expect(page.getByAltText('Green circle')).toBeVisible();
  await expect(page.getByTitle('Notes saved today')).toHaveText('0');
});

Output:

Running 2 tests using 2 workers

[1/2] [chromium] › tests/builtins.spec.js:4:1 › log in with built-in locators
[2/2] [chromium] › tests/builtins.spec.js:14:1 › find by alt text and title
  2 passed (3.7s)

Text matching is case-insensitive and matches a part of the text by default.

Add { exact: true } to match the whole text, with the same case:

Example

page.getByText('Welcome, student!', { exact: true })

Tip: Not sure which locator to use? Run npx playwright codegen and click an element.

Playwright suggests the best locator for it.

You will learn more in the Codegen chapter.



CSS and XPath

You can also find elements with a CSS selector or an XPath expression, with page.locator():

Example

tests/css.spec.js

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

test('CSS and XPath locators', async ({ page }) => {
  await page.goto('https://www.w3schools.com/playwright/practice/todo.html');
  await page.locator('#new-todo').fill('Buy milk');
  await page.locator('xpath=//button[text()="Add"]').click();
  await expect(page.locator('.todo-list li')).toHaveCount(1);
});

The test works, but it depends on ids, class names and the structure of the page.

Those are details a user never sees, and they often change when developers update the design.

When they change, the test breaks, even though the page still works.

Use the built-in locators when you can, and keep CSS and XPath for the rare cases where nothing else works.

When a locator finds several elements, the next chapter, Filter Locators, shows how to pick the one you want.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.