Skip to contentPlayForge

What is a locator in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

A locator is Playwright's way of finding an element on the page at the moment you act on it. Every action and assertion through a locator waits and retries until the element is ready, which is why locators are the centre of Playwright's auto-waiting.

This answer is one piece of Chapter 9: Locators I: What the User Sees.

  • getByRole and the Accessible Name
  • getByText, getByLabel, getByPlaceholder, getByTestId
  • Strict Mode — One Locator, One Element

A locator is not the element itself. It is a description of how to find it, such as "the Add to cart button inside the grinder's card". Playwright looks the element up again each time you use the locator, so a page that re-renders does not leave you holding a stale element.

Playwright recommends locating elements the way a user sees them: by role and accessible name with getByRole(), or by an explicit test id with getByTestId(). Those survive changes to CSS classes and layout far better than long CSS or XPath paths.

In the example, grinder narrows the search to one product card, then getByRole('button', { name: 'Add to cart' }) finds the button inside it. The assertion toHaveText('₹11,900') retries until the cart total matches.

fixed.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('adding the grinder updates the cart total', async ({ page }) => { await page.goto('/catalog.html?mock=static&seed=42&autologin=1'); const grinder = page.locator('article[data-sku="MRD-1003"]'); await grinder.getByRole('button', { name: 'Add to cart' }).click(); await expect(page.getByTestId('cart-total')).toHaveText('₹11,900'); });
Output
1 passed (7.9s)
Source:Locators
Test yourself
You create const add = page.getByRole('button', { name: 'Add to cart' }). The page then re-renders and replaces that button with a new one. What does await add.click() do?

Practised in the full course: the drill The button you can see.

See the chapter

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.