Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Playwright Locators

Playwright Locators

Locator is one of the most core concepts in Playwright; it represents a way to find elements on a page.

This chapter introduces Playwright's recommended locating methods: locating elements by role, text, tag, and placeholder.


What is a Locator

Locator is an abstract object Playwright uses to find elements on a page.

Compared with traditional document.querySelector() Unlike other tools, Playwright's Locator has automatic waiting and automatic retry capabilities.

When page content changes dynamically, the Locator keeps re-finding the element until a match is found or a timeout occurs.

Example

// Create a Locator (the element is not searched immediately at this point)

const

button

=

page.

getByRole

(

'button'

,

{

name

:

'Submit'

}

)

;

// When performing an action, Playwright automatically waits for the button to appear and become actionable

await button.

click

(

)

;

How Locator works

When a Locator is created, Playwright only records a lookup rule.

When you call .click()、.fill() operations or expect(locator) assertions, the Locator actually begins searching for elements.

If the element cannot be found, the Locator keeps retrying until the operation times out.


Locating by role: getByRole()

getByRole() is Playwright's most recommended locating method.

It finds elements by their accessibility role (ARIA Role), which is the closest to user perception.

Basic Usage

Example

// Locate a button — by role "button"

const

submitBtn

=

page.

getByRole

(

'button'

,

{

name

:

'Submit'

}

)

;

await submitBtn.

click

(

)

;

// Locate a link — by role "link"

const

homeLink

=

page.

getByRole

(

'link'

,

{

name

:

'Home'

}

)

;

await homeLink.

click

(

)

;

// Locate a heading — by role "heading"

const

mainTitle

=

page.

getByRole

(

'heading'

,

{

name

:

'Welcome to RUNOOB'

}

)

;

// Locate a textbox — by role "textbox"

const

searchBox

=

page.

getByRole

(

'textbox'

,

{

name

:

'Search'

}

)

;

await searchBox.

fill

(

'Playwright'

)

;

Common ARIA Roles

Role Corresponding HTML elements Usage examples
'button' getByRole('button', { name: '登录' })
'link' getByRole('link', { name: '了解更多' })
'heading'

~

getByRole('heading', { name: 'RUNOOB 教程' })
'textbox' 、

await page.

getByPlaceholder

(

'Share your thoughts...'

)

.

fill

(

'RUNOOB tutorial is great!'

)

;

Choosing between getByLabel and getByPlaceholder

Method Applicable scenarios Precedence
getByLabel() Yes Priority use
getByPlaceholder() When there is no label but there is a placeholder Second choice

getByRole is the most recommended locator in Playwright because it mimics the way users identify elements by role. Next is getByLabel and getByPlaceholder. Only consider using it when there are no semantic elements getByTestId or CSS selectors.


getByAltText() image locating

getByAltText() Via the image's alt attribute to locate .

Example

// HTML:RUNOOB Logo

await expect

(

page.

getByAltText

(

'RUNOOB Logo'

)

)

.

toBeVisible

(

)

;

// Regular expression match

await expect

(

page.

getByAltText

(

/logo/i

)

)

.

toBeVisible

(

)

;


getByTitle() title attribute locator

getByTitle() Through the element's title attribute to locate.

Example

// HTML:

await page.

getByTitle

(

'Close current page'

)

.

click

(

)

;

getByAltText and getByTitle Used less frequently, only when an element has a clear alt or title attribute and cannot be located by other means.


getByTestId() test ID locating

getByTestId() It is a fallback, via data-testid attribute.

Example

// HTML:

await page.

getByTestId

(

'submit-btn'

)

.

click

(

)

;

// Can contain multiple matches (such as list items)

const

items

=

page.

getByTestId

(

'todo-item'

)

;

await expect

(

items

)

.

toHaveCount

(

3

)

;

Custom testId attribute

If your project does not use data-testid, allowing the playwright.config.ts Custom attribute name in :

Example

// File path: playwright.config.ts

export

default

defineConfig

(

{

  use

:

{

   

// Use data-cy instead of data-testid (for Cypress migration)

    testIdAttribute

:

'data-cy'

,

   

// or use id as testId

   

// testIdAttribute: 'id',

 

}

,

}

)

;


page.locator() CSS and XPath locating

page.locator() Supports CSS selectors and XPath, a more flexible fallback.

CSS selector

Example

// By CSS class name

await page.

locator

(

'.submit-btn'

)

.

click

(

)

;

// By ID

await page.

locator

(

'#username'

)

.

fill

(

'runoob_user'

)

;

// By attribute

await page.

locator

(

'[data-type="primary"]'

)

.

click

(

)

;

// by combining tag + class name

await page.

locator

(

'button.primary'

)

.

click

(

)

;

// Via the parent-child relationship

await page.

locator

(

'nav a'

)

.

first

(

)

.

click

(

)

;

// CSS selector for specific text

await page.

locator

(

'button:has-text("Submit")'

)

.

click

(

)

;

XPath locating

Example

// Locate using XPath

await page.

locator

(

'xpath=//button[@type="submit"]'

)

.

click

(

)

;

// Locate by text

await page.

locator

(

'xpath=//h1[contains(text(), "RUNOOB")]'

)

.

click

(

)

;

CSS selectors and XPath are the last resort; prefer using getByRole、getByText and other semantic locating methods. CSS selectors easily break due to style refactoring, XPath is poorly readable and slower in performance.


Locator chained operations

Playwright's Locator supports chained calls, allowing further filtering on the current matching results.

.first()、.last()、.nth()

Example

// Get the first matching list item

const

firstItem

=

page.

getByRole

(

'listitem'

)

.

first

(

)

;

// take the last one

const

lastItem

=

page.

getByRole

(

'listitem'

)

.

last

(

)

;

// Get the 2nd one (index starts at 0)

const

secondItem

=

page.

getByRole

(

'listitem'

)

.

nth

(

1

)

;

.filter() filtering

Example

// Filter from all buttons those containing specific text

page.

getByRole

(

'button'

)

.

filter

(

{

hasText

:

'Save'

}

)

;

// Filter out those that do not contain specific text

page.

getByRole

(

'listitem'

)

.

filter

(

{

hasNotText

:

'Deleted'

}

)

;

// Filter for those containing a specific child element

page.

getByRole

(

'listitem'

)

.

filter

(

{

has

:

page.

getByRole

(

'button'

)

}

)

;

// filter out those that do not contain a specific child element

page.

getByRole

(

'listitem'

)

.

filter

(

{

hasNot

:

page.

getByTestId

(

'badge'

)

}

)

;

.locator() child element locating

Example

// first locate the list container, then find the button inside the container

const

list

=

page.

getByTestId

(

'todo-list'

)

;

const

deleteBtn

=

list.

locator

(

'button.delete'

)

;

await deleteBtn.

click

(

)

;

// Multi-level nesting

page

  .

getByRole

(

'dialog'

)

  .

locator

(

'div.content'

)

  .

locator

(

'button'

)

  .

filter

(

{

hasText

:

'Confirm'

}

)

  .

click

(

)

;

.and() and .or() logical combinations (1.63+)

Example

// Satisfy both conditions at the same time

const

btn

=

page.

getByRole

(

'button'

)

  .

and

(

page.

getByText

(

'Submit'

)

)

;

// Satisfy any one condition

const

target

=

page.

getByText

(

'RUNOOB'

)

  .

or

(

page.

getByTitle

(

'RUNOOB'

)

)

;


Summary of Locator locating method priorities

Arranged from highest to lowest degree of recommendation:

Precedence Method Usage conditions
1 (most recommended) getByRole() Element has a clear ARIA role
2 getByLabel() The form element has an associated label
3 getByPlaceholder() Input box has a placeholder
4 getByText() The element has explicit text content
5 getByAltText() Image has an alt attribute
6 getByTitle() Element has a title attribute
7 (fallback) getByTestId() When none of the above methods can locate it
8 (last choice) locator() CSS selector / XPath