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'
、role="button"
getByRole('button', { name: '登录' })
'link'
getByRole('link', { name: '了解更多' })
'heading'
~
getByRole('heading', { name: 'RUNOOB 教程' })
'textbox'
、
getByRole('textbox', { name: '用户名' })
'checkbox'
getByRole('checkbox', { name: '记住我' })
'radio'
getByRole('radio', { name: '男' })
'combobox'
getByRole('combobox', { name: '城市' })
'img'
getByRole('img', { name: 'Logo' })
'list'
、
getByRole('list')
'listitem'
getByRole('listitem')
'navigation'
getByRole('navigation')
'table'
getByRole('table')
the name option
name The option narrows the scope by the accessible name of the element.
Sources of the accessible name include: element text content, aria-label Attribute, associated , etc.
Example
// Match by button text
page.
getByRole
(
'button'
,
{
name
:
'Login'
}
)
;
// Match by aria-label
page.
getByRole
(
'button'
,
{
name
:
'Close dialog'
}
)
;
// regular expression matching
page.
getByRole
(
'link'
,
{
name
:
/RUNOOB|rookie/
}
)
;
State Options
Besides name,getByRole Also supports multiple state options:
Example
// Locate checked checkboxes
page.
getByRole
(
'checkbox'
,
{
checked
:
true
}
)
;
// locate disabled buttons
page.
getByRole
(
'button'
,
{
disabled
:
true
}
)
;
// Locate the expanded dropdown menu
page.
getByRole
(
'button'
,
{
expanded
:
true
}
)
;
// Locate the selected option
page.
getByRole
(
'option'
,
{
selected
:
true
}
)
;
// Combine multiple states
page.
getByRole
(
'checkbox'
,
{
name
:
'Agree to the terms'
,
checked
:
false
}
)
;
Locating by text: getByText()
getByText() Locate by the element's text content.
Example
// Exact text match
page.
getByText
(
'Welcome to RUNOOB'
)
;
// Partial match (default)
page.
getByText
(
'RUNOOB'
)
;
// Force exact matching
page.
getByText
(
'RUNOOB'
,
{
exact
:
true
}
)
;
// regular expression matching
page.
getByText
(
/RUNOOB|Runoob Tutorial/
)
;
getByText What is matched is the complete text content of the element, so getByText('RUNOOB', { exact: true }) Only matches elements whose text content is exactly "RUNOOB".
By default, when exact matching is not enabled, substring matching is sufficient (e.g. getByText('RUNOOB') will match "Welcome to RUNOOB").
Locate by label: getByLabel()
getByLabel() Used to locate and The associated form control.
Example
// HTML structure:
//
//
// Locate input by label text
await page.
getByLabel
(
'Username'
)
.
fill
(
'runoob_user'
)
;
// HTML structure:
//
// Nested labels work as well
await page.
getByLabel
(
'Password'
)
.
fill
(
'password123'
)
;
It also supports { exact: true } Exact matching option.
Locate by placeholder: getByPlaceholder()
getByPlaceholder() Pass placeholder Locate the input box by attribute.
Example
// HTML structure:
await page.
getByPlaceholder
(
'Please enter search keywords'
)
.
fill
(
'Playwright'
)
;
// HTML structure:
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:
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: