2021-12-08 20:54:01 +03:00
---
id: locators
title: "Locators"
---
2022-08-17 08:00:54 +03:00
[Locator]s are the central piece of Playwright's auto-waiting and retry-ability. In a nutshell, locators represent
2022-10-27 01:30:22 +03:00
a way to find element(s) on the page at any moment.
2021-12-08 20:54:01 +03:00
2022-10-29 00:49:25 +03:00
### Quick Guide
These are the recommended built in locators.
2022-11-11 18:23:00 +03:00
- [`method: Page.getByRole` ](#locate-by-role ) to locate by explicit and implicit accessibility attributes.
2022-11-02 23:35:51 +03:00
- [`method: Page.getByText` ](#locate-by-text ) to locate by text content.
2022-11-11 18:23:00 +03:00
- [`method: Page.getByLabel` ](#locate-by-label ) to locate a form control by associated label's text.
- [`method: Page.getByPlaceholder` ](#locate-by-placeholder ) to locate an input by placeholder.
2022-11-02 23:35:51 +03:00
- [`method: Page.getByAltText` ](#locate-by-alt-text ) to locate an element, usually image, by its text alternative.
2022-11-11 18:23:00 +03:00
- [`method: Page.getByTitle` ](#locate-by-title ) to locate an element by its title attribute.
2022-11-29 07:00:30 +03:00
- [`method: Page.getByTestId` ](#locate-by-test-id ) to locate an element based on its `data-testid` attribute (other attributes can be configured).
2022-10-29 00:49:25 +03:00
2021-12-08 20:54:01 +03:00
```js
2022-10-29 00:49:25 +03:00
await page.getByLabel('User Name').fill('John');
await page.getByLabel('Password').fill('secret-password');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByText('Welcome, John!')).toBeVisible();
2021-12-08 20:54:01 +03:00
```
```java
2022-10-29 00:49:25 +03:00
page.getByLabel("User Name").fill("John");
page.getByLabel("Password").fill("secret-password");
2022-11-16 20:54:40 +03:00
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in"))
.click();
2022-10-29 00:49:25 +03:00
assertThat(page.getByText("Welcome, John!")).isVisible();
2021-12-08 20:54:01 +03:00
```
```python async
2022-10-29 00:49:25 +03:00
await page.get_by_label("User Name").fill("John")
await page.get_by_label("Password").fill("secret-password")
await page.get_by_role("button", name="Sign in").click()
await expect(page.get_by_text("Welcome, John!")).to_be_visible()
2021-12-08 20:54:01 +03:00
```
```python sync
2022-10-29 00:49:25 +03:00
page.get_by_label("User Name").fill("John")
page.get_by_label("Password").fill("secret-password")
page.get_by_role("button", name="Sign in").click()
expect(page.get_by_text("Welcome, John!")).to_be_visible()
2021-12-08 20:54:01 +03:00
```
```csharp
2022-10-29 00:49:25 +03:00
await page.GetByLabel("User Name").FillAsync("John");
await page.GetByLabel("Password").FillAsync("secret-password");
2022-11-30 07:56:18 +03:00
await page.GetByRole(AriaRole.Button, new() { Name = "Sign in" }).ClickAsync();
2022-10-29 00:49:25 +03:00
await Expect(page.GetByText("Welcome, John!")).ToBeVisibleAsync();
2021-12-08 20:54:01 +03:00
```
2022-11-11 18:23:00 +03:00
## Locating elements
2021-12-08 20:54:01 +03:00
2022-11-30 07:56:18 +03:00
Playwright comes with multiple built-in locators. To make tests resilient, we recommend prioritizing user-facing attributes and explicit contracts such as [`method: Page.getByRole`].
2022-11-11 18:23:00 +03:00
For example, consider the following DOM structure.
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< button > Sign in< / button >
2021-12-08 20:54:01 +03:00
```
2022-11-16 00:13:16 +03:00
2022-11-11 18:23:00 +03:00
Locate the element by its role of `button` with name "Sign in".
2021-12-08 20:54:01 +03:00
2022-11-11 18:23:00 +03:00
```js
2022-11-16 20:54:40 +03:00
await page.getByRole('button', { name: 'Sign in' }).click();
2022-11-11 18:23:00 +03:00
```
2022-11-16 20:54:40 +03:00
2021-12-08 20:54:01 +03:00
```java
2022-11-11 18:23:00 +03:00
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in"))
.click();
2021-12-08 20:54:01 +03:00
```
2022-11-16 20:54:40 +03:00
2021-12-08 20:54:01 +03:00
```python async
2022-11-11 18:23:00 +03:00
await page.get_by_role("button", name="Sign in").click()
2021-12-08 20:54:01 +03:00
```
2022-11-16 20:54:40 +03:00
2021-12-08 20:54:01 +03:00
```python sync
2022-11-11 18:23:00 +03:00
page.get_by_role("button", name="Sign in").click()
2021-12-08 20:54:01 +03:00
```
2022-11-16 20:54:40 +03:00
2021-12-08 20:54:01 +03:00
```csharp
2022-11-30 07:56:18 +03:00
await page.GetByRole(AriaRole.Button, new() { Name = "Sign in" }).ClickAsync();
2021-12-08 20:54:01 +03:00
```
2022-11-11 18:23:00 +03:00
:::tip
Use the [code generator ](./codegen.md ) to generate a locator, and then edit it as you'd like.
:::
2021-12-08 20:54:01 +03:00
2022-11-11 18:23:00 +03:00
Every time a locator is used for an action, an up-to-date DOM element is located in the page. In the snippet
below, the underlying DOM element will be located twice, once prior to every action. This means that if the
DOM changes in between the calls due to re-render, the new element corresponding to the
locator will be used.
2021-12-08 20:54:01 +03:00
```js
2022-11-11 18:23:00 +03:00
const locator = page.getByRole('button', { name: 'Sign in' })
2021-12-08 20:54:01 +03:00
2022-11-11 18:23:00 +03:00
await locator.hover();
await locator.click();
2021-12-08 20:54:01 +03:00
```
```java
2022-11-16 20:54:40 +03:00
Locator locator = page.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Sign in"))
2021-12-08 20:54:01 +03:00
2022-11-11 18:23:00 +03:00
locator.hover();
locator.click();
2022-10-27 01:30:22 +03:00
```
2021-12-08 20:54:01 +03:00
2022-10-27 01:30:22 +03:00
```python async
2022-11-11 18:23:00 +03:00
locator = page.get_by_role("button", name="Sign in")
await locator.hover()
await locator.click()
2022-10-27 01:30:22 +03:00
```
```python sync
2022-11-11 18:23:00 +03:00
locator = page.get_by_role("button", name="Sign in")
2022-10-27 01:30:22 +03:00
2022-11-11 18:23:00 +03:00
locator.hover()
locator.click()
2022-10-27 01:30:22 +03:00
```
```csharp
2022-11-30 07:56:18 +03:00
var locator = page.GetByRole(AriaRole.Button, new() { Name = "Sign in" })
2021-12-08 20:54:01 +03:00
2022-11-11 18:23:00 +03:00
await locator.HoverAsync();
await locator.ClickAsync();
2022-10-27 01:30:22 +03:00
```
Note that all methods that create a locator, such as [`method: Page.getByLabel`], are also available on the [Locator] and [FrameLocator] classes, so you can chain them and iteratively narrow down your locator.
```js
2022-11-16 20:54:40 +03:00
const locator = page
.frameLocator('#my-frame')
2022-11-11 18:23:00 +03:00
.getByRole('button', { name: 'Sign in' });
2022-10-27 01:30:22 +03:00
await locator.click();
```
```java
2022-11-16 20:54:40 +03:00
Locator locator = page
.frameLocator("#my-frame")
2022-11-11 18:23:00 +03:00
.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in"));
2022-10-27 01:30:22 +03:00
locator.click();
```
```python async
2022-11-16 20:54:40 +03:00
locator = page.frame_locator("#my-frame").get_by_role("button", name="Sign in")
2022-11-11 18:23:00 +03:00
2022-10-27 01:30:22 +03:00
await locator.click()
```
```python sync
2022-11-16 20:54:40 +03:00
locator = page.frame_locator("my-frame").get_by_role("button", name="Sign in")
2022-11-11 18:23:00 +03:00
2022-10-27 01:30:22 +03:00
locator.click()
```
```csharp
2022-11-16 20:54:40 +03:00
var locator = page
.FrameLocator("#my-frame")
2022-11-30 07:56:18 +03:00
.GetByRole(AriaRole.Button), new() { Name = "Sign in" });
2022-11-11 18:23:00 +03:00
2022-10-27 01:30:22 +03:00
await locator.ClickAsync();
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
### Locate by role
The [`method: Page.getByRole`] locator reflects how users and assistive technology perceive the page, for example whether some element is a button or a checkbox. When locating by role, you should usually pass the accessible name as well, so that the locator pinpoints the exact element.
For example, consider the following DOM structure.
2022-11-16 20:54:40 +03:00
```html card
2022-11-16 00:13:16 +03:00
< h3 > Sign up< / h3 >
2022-11-16 20:54:40 +03:00
< label >
< input type = "checkbox" / > Subscribe
< / label >
< br / >
< button > Submit< / button >
2022-11-11 18:23:00 +03:00
```
You can locate each element by it's implicit role:
2022-10-29 00:49:25 +03:00
```js
2022-11-16 20:54:40 +03:00
await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible()
2022-11-11 18:23:00 +03:00
2022-11-16 20:54:40 +03:00
await page.getByRole('checkbox', { name: 'Subscribe' }).check();
2022-10-29 00:49:25 +03:00
2022-11-16 20:54:40 +03:00
await page.getByRole('button', { name: /submit/i }).click();
2022-10-29 00:49:25 +03:00
```
```python async
2022-11-16 00:13:16 +03:00
await expect(page.get_by_role("heading", name="Sign up")).to_be_visible()
2022-11-11 18:23:00 +03:00
2022-11-16 00:13:16 +03:00
await page.get_by_role("checkbox", name="Subscribe").check()
2022-10-29 00:49:25 +03:00
2022-11-11 18:23:00 +03:00
await page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
2022-10-29 00:49:25 +03:00
```
```python sync
2022-11-16 00:13:16 +03:00
expect(page.get_by_role("heading", name="Sign up")).to_be_visible()
2022-10-29 00:49:25 +03:00
2022-11-16 00:13:16 +03:00
page.get_by_role("checkbox", name="Subscribe").check()
2022-11-11 18:23:00 +03:00
page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
2022-10-29 00:49:25 +03:00
```
```java
2022-11-16 20:54:40 +03:00
assertThat(page
.getByRole(AriaRole.HEADING,
new Page.GetByRoleOptions().setName("Sign up")))
2022-11-11 18:23:00 +03:00
.isVisible();
2022-10-29 00:49:25 +03:00
2022-11-16 20:54:40 +03:00
page.getByRole(AriaRole.CHECKBOX,
new Page.GetByRoleOptions().setName("Subscribe"))
2022-11-16 00:13:16 +03:00
.check();
2022-11-11 18:23:00 +03:00
2022-11-16 20:54:40 +03:00
page.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName(
Pattern.compile("submit", Pattern.CASE_INSENSITIVE)))
2022-11-11 18:23:00 +03:00
.click();
2022-10-29 00:49:25 +03:00
```
```csharp
2022-11-16 20:54:40 +03:00
await Expect(page
2022-11-30 07:56:18 +03:00
.GetByRole(AriaRole.Heading, new() { Name = "Sign up" }))
2022-11-11 18:23:00 +03:00
.ToBeVisibleAsync();
2022-11-16 20:54:40 +03:00
await page
2022-11-30 07:56:18 +03:00
.GetByRole(AriaRole.Checkbox, new() { Name = "Subscribe" })
2022-11-16 00:13:16 +03:00
.CheckAsync();
2022-10-29 00:49:25 +03:00
2022-11-16 20:54:40 +03:00
await page
.GetByRole(AriaRole.Button, new() {
NameRegex = new Regex("submit", RegexOptions.IgnoreCase)
})
2022-11-11 18:23:00 +03:00
.ClickAsync();
2022-10-29 00:49:25 +03:00
```
2022-12-03 08:48:37 +03:00
Role locators include [buttons, checkboxes, headings, links, lists, tables, and many more ](https://www.w3.org/TR/html-aria/#docconformance ) and follow W3C specifications for [ARIA role ](https://www.w3.org/TR/wai-aria-1.2/#roles ), [ARIA attributes ](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes ) and [accessible name ](https://w3c.github.io/accname/#dfn-accessible-name ). Note that many html elements like `<button>` have an [implicitly defined role ](https://w3c.github.io/html-aam/#html-element-role-mappings ) that is recognized by the role locator.
2022-10-29 00:49:25 +03:00
Note that role locators **do not replace** accessibility audits and conformance tests, but rather give early feedback about the ARIA guidelines.
2022-11-11 18:23:00 +03:00
:::tip When to use role locators
We recommend prioritizing role locators to locate elements, as it is the closest way to how users and assistive technology perceive the page.
:::
### Locate by label
2022-10-29 00:49:25 +03:00
Most form controls usually have dedicated labels that could be conveniently used to interact with the form. In this case, you can locate the control by its associated label using [`method: Page.getByLabel`].
For example, consider the following DOM structure.
2022-11-16 20:54:40 +03:00
```html card
< label > Password < input type = "password" / > < / label >
2022-10-29 00:49:25 +03:00
```
You can fill the input after locating it by the label text:
```js
await page.getByLabel('Password').fill('secret');
```
```java
page.getByLabel("Password").fill("secret");
```
```python async
await page.get_by_label("Password").fill("secret")
```
```python sync
page.get_by_label("Password").fill("secret")
```
```csharp
await page.GetByLabel("Password").FillAsync("secret");
```
2022-11-16 00:13:16 +03:00
2022-11-11 18:23:00 +03:00
:::tip When to use label locators
Use this locator when locating form fields.
:::
### Locate by placeholder
2022-10-29 00:49:25 +03:00
Inputs may have a placeholder attribute to hint to the user what value should be entered. You can locate such an input using [`method: Page.getByPlaceholder`].
For example, consider the following DOM structure.
2022-11-16 20:54:40 +03:00
```html card
< input type = "email" placeholder = "name@example.com" / >
2022-10-29 00:49:25 +03:00
```
You can fill the input after locating it by the placeholder text:
```js
2022-11-16 20:54:40 +03:00
await page
.getByPlaceholder("name@example.com")
2022-11-11 18:23:00 +03:00
.fill("playwright@microsoft.com");
2022-10-29 00:49:25 +03:00
```
```java
2022-11-16 20:54:40 +03:00
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
2022-10-29 00:49:25 +03:00
```
```python async
await page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")
```
```python sync
page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")
```
```csharp
2022-11-16 20:54:40 +03:00
await page
.GetByPlaceholder("name@example.com")
2022-11-11 18:23:00 +03:00
.FillAsync("playwright@microsoft.com");
2022-10-29 00:49:25 +03:00
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
:::tip When to use placeholder locators
Use this locator when locating form elements that do not have labels but do have placeholder texts.
:::
2022-10-29 00:49:25 +03:00
### Locate by text
2022-10-27 01:30:22 +03:00
2022-11-11 18:23:00 +03:00
Find an element by the text it contains. You can match by a substring, exact string, or a regular expression when using [`method: Page.getByText`].
For example, consider the following DOM structure.
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< span > Welcome, John< / span >
```
You can locate the element by the text it contains:
```js
2022-11-16 20:54:40 +03:00
await expect(page.getByText('Welcome, John')).toBeVisible();
2022-11-11 18:23:00 +03:00
```
```java
2022-11-16 20:54:40 +03:00
assertThat(page.getByText("Welcome, John")).isVisible();
2022-11-11 18:23:00 +03:00
```
```python async
await expect(page.get_by_text("Welcome, John")).to_be_visible()
```
```python sync
expect(page.get_by_text("Welcome, John")).to_be_visible()
```
```csharp
2022-11-16 20:54:40 +03:00
await Expect(page.GetByText("Welcome, John")).ToBeVisibleAsync();
2022-11-11 18:23:00 +03:00
```
2021-12-08 20:54:01 +03:00
2022-11-11 18:23:00 +03:00
Set an exact match:
2021-12-08 20:54:01 +03:00
```js
2022-11-16 20:54:40 +03:00
await expect(page.getByText('Welcome, John', { exact: true })).toBeVisible();
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
2022-09-30 21:14:13 +03:00
```java
2022-11-16 20:54:40 +03:00
assertThat(page
.getByText("Welcome, John", new Page.GetByTextOptions().setExact(true)))
2022-11-11 18:23:00 +03:00
.isVisible();
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
2022-09-30 21:14:13 +03:00
```python async
2022-11-11 18:23:00 +03:00
await expect(page.get_by_text("Welcome, John", exact=True)).to_be_visible()
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
2022-09-30 21:14:13 +03:00
```python sync
2022-11-11 18:23:00 +03:00
expect(page.get_by_text("Welcome, John", exact=True)).to_be_visible()
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
2022-09-30 21:14:13 +03:00
```csharp
2022-11-16 20:54:40 +03:00
await Expect(page
.GetByText("Welcome, John", new() { Exact = true }))
2022-11-11 18:23:00 +03:00
.ToBeVisibleAsync();
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
Match with a regular expression:
2022-09-30 21:14:13 +03:00
```js
2022-11-16 20:54:40 +03:00
await expect(page.getByText(/welcome, [A-Za-z]+$/i)).toBeVisible();
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
2022-09-30 21:14:13 +03:00
```java
2022-11-16 20:54:40 +03:00
assertThat(page
.getByText(Pattern.compile("welcome, john$", Pattern.CASE_INSENSITIVE)))
.isVisible();
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
2022-09-30 21:14:13 +03:00
```python async
2022-11-16 20:54:40 +03:00
await expect(page
.get_by_text(re.compile("welcome, john", re.IGNORECASE)))
.to_be_visible()
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
2022-09-30 21:14:13 +03:00
```python sync
2022-11-16 20:54:40 +03:00
expect(page
.get_by_text(re.compile("welcome, john", re.IGNORECASE)))
.to_be_visible()
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
2022-09-30 21:14:13 +03:00
```csharp
2022-11-16 20:54:40 +03:00
await Expect(page
.GetByText(new Regex("welcome, john", RegexOptions.IgnoreCase)))
2022-11-11 18:23:00 +03:00
.ToBeVisibleAsync();
2022-09-30 21:14:13 +03:00
```
2021-12-08 20:54:01 +03:00
2022-10-27 20:27:18 +03:00
:::note
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
:::
2022-11-11 18:23:00 +03:00
:::tip When to use text locators
We recommend using text locators to find non interactive elements like `div` , `span` , `p` , etc. For interactive elements like `button` , `a` , `input` , etc. use [role locators ](#locate-by-role ).
:::
You can also [filter by text ](#filter-by-text ) which can be useful when trying to find a particular item in a list.
2022-10-29 00:49:25 +03:00
### Locate by alt text
2021-12-08 20:54:01 +03:00
2022-10-29 00:49:25 +03:00
All images should have an `alt` attribute that describes the image. You can locate an image based on the text alternative using [`method: Page.getByAltText`].
2022-09-30 21:14:13 +03:00
2022-10-29 00:49:25 +03:00
For example, consider the following DOM structure.
2022-09-30 21:14:13 +03:00
2022-11-16 20:54:40 +03:00
```html card
< img alt = "playwright logo" src = "/img/playwright-logo.svg" width = "100" / >
2022-09-30 21:14:13 +03:00
```
2022-10-29 00:49:25 +03:00
You can click on the image after locating it by the text alternative:
2022-09-30 21:14:13 +03:00
2022-10-29 00:49:25 +03:00
```js
2022-11-16 20:54:40 +03:00
await page.getByAltText('playwright logo').click();
2022-09-30 21:14:13 +03:00
```
2021-12-08 20:54:01 +03:00
2022-09-30 21:14:13 +03:00
```java
2022-11-16 20:54:40 +03:00
page.getByAltText("playwright logo").click();
2022-09-30 21:14:13 +03:00
```
2022-10-29 00:49:25 +03:00
```python async
await page.get_by_alt_text("playwright logo").click()
2022-09-30 21:14:13 +03:00
```
2022-10-29 00:49:25 +03:00
```python sync
page.get_by_alt_text("playwright logo").click()
```
2022-09-30 21:14:13 +03:00
2022-10-29 00:49:25 +03:00
```csharp
2022-11-16 20:54:40 +03:00
await page.GetByAltText("playwright logo").ClickAsync();
2022-11-16 00:13:16 +03:00
```
2022-11-11 18:23:00 +03:00
:::tip When to use alt locators
Use this locator when your element supports alt text such as `img` and `area` elements.
:::
2022-10-29 00:49:25 +03:00
### Locate by title
2022-09-30 21:14:13 +03:00
2022-10-29 00:49:25 +03:00
Locate an element with a matching title attribute using [`method: Page.getByTitle`].
2022-10-27 01:30:22 +03:00
2022-10-29 00:49:25 +03:00
For example, consider the following DOM structure.
2022-09-30 21:14:13 +03:00
2022-11-16 20:54:40 +03:00
```html card
2022-10-29 00:49:25 +03:00
< span title = 'Issues count' > 25 issues< / span >
2022-09-30 21:14:13 +03:00
```
2022-10-29 00:49:25 +03:00
You can check the issues count after locating it by the title text:
2022-09-30 21:14:13 +03:00
```js
2022-11-16 20:54:40 +03:00
await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
2022-09-30 21:14:13 +03:00
```
```java
2022-11-16 20:54:40 +03:00
assertThat(page.getByTitle("Issues count")).hasText("25 issues");
2022-09-30 21:14:13 +03:00
```
```python async
2022-10-29 00:49:25 +03:00
await expect(page.get_by_title("Issues count")).to_have_text("25 issues")
2021-12-08 20:54:01 +03:00
```
```python sync
2022-10-29 00:49:25 +03:00
expect(page.get_by_title("Issues count")).to_have_text("25 issues")
2022-09-30 21:14:13 +03:00
```
```csharp
2022-11-16 20:54:40 +03:00
await Expect(page.GetByTitle("Issues count")).toHaveText("25 issues");
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
:::tip When to use title locators
Use this locator when your element has the `title` attribute.
:::
### Locate by test id
2021-12-08 20:54:01 +03:00
2022-11-11 18:23:00 +03:00
Testing by test ids is the most resilient way of testing as even if your text or role of the attribute changes the test will still pass. QA's and developers should define explicit test ids and query them with [`method: Page.getByTestId`]. However testing by test ids is not user facing. If the role or text value is important to you then consider using user facing locators such as [role ](#locate-by-role ) and [text locators ](#locate-by-text ).
For example, consider the following DOM structure.
2021-12-08 20:54:01 +03:00
2022-11-16 20:54:40 +03:00
```html card
2022-10-29 00:49:25 +03:00
< button data-testid = "directions" > Itinéraire< / button >
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
You can locate the element by it's test id:
2022-09-30 21:14:13 +03:00
```js
2022-11-16 20:54:40 +03:00
await page.getByTestId('directions').click();
2021-12-08 20:54:01 +03:00
```
```java
2022-11-16 20:54:40 +03:00
page.getByTestId("directions").click();
2022-09-30 21:14:13 +03:00
```
2021-12-08 20:54:01 +03:00
2022-09-30 21:14:13 +03:00
```python async
2022-10-29 00:49:25 +03:00
await page.get_by_test_id("directions").click()
2022-09-30 21:14:13 +03:00
```
2021-12-08 20:54:01 +03:00
2022-09-30 21:14:13 +03:00
```python sync
2022-10-29 00:49:25 +03:00
page.get_by_test_id("directions").click()
2022-09-30 21:14:13 +03:00
```
2021-12-08 20:54:01 +03:00
2022-09-30 21:14:13 +03:00
```csharp
2022-11-16 20:54:40 +03:00
await page.GetByTestId("directions").ClickAsync();
2022-11-16 00:13:16 +03:00
```
2022-10-29 00:49:25 +03:00
2022-11-11 18:23:00 +03:00
:::tip When to use testid locators
You can also use test ids when you choose to use the test id methodology or when you can't locate by [role ](#locate-by-role ) or [text ](#locate-by-text ).
:::
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
#### Set a custom test id attribute
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
By default, [`method: Page.getByTestId`] will locate elements based on the `data-testid` attribute, but you can configure it in your test config or by calling [`method: Selectors.setTestIdAttribute`].
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
Set the test id to use a custom data attribute for your tests.
```js tab=js-js
// playwright.config.js
// @ts -check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
use: {
testIdAttribute: 'data-pw'
},
};
module.exports = config;
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
```js tab=js-ts
// playwright.config.ts
import type { PlaywrightTestConfig } from '@playwright/test';
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
const config: PlaywrightTestConfig = {
use: {
testIdAttribute: 'data-pw'
}
};
export default config;
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
```java
playwright.selectors().setTestIdAttribute("data-pw");
2022-09-30 21:14:13 +03:00
```
```python async
2022-11-11 18:23:00 +03:00
playwright.selectors.set_test_id_attribute("data-pw")
2022-09-30 21:14:13 +03:00
```
```python sync
2022-11-11 18:23:00 +03:00
playwright.selectors.set_test_id_attribute("data-pw")
```
```csharp
playwright.Selectors.SetTestIdAttribute("data-pw");
```
2022-11-30 07:56:18 +03:00
In your html you can now use `data-pw` as your test id instead of the default `data-testid` .
2022-09-30 21:14:13 +03:00
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< button data-pw = "directions" > Itinéraire< / button >
```
And then locate the element as you would normally do:
```js
2022-11-16 20:54:40 +03:00
await page.getByTestId('directions').click();
2022-09-30 21:14:13 +03:00
```
```java
2022-11-16 20:54:40 +03:00
page.getByTestId("directions").click();
2022-11-11 18:23:00 +03:00
```
```python async
await page.get_by_test_id("directions").click()
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
```python sync
page.get_by_test_id("directions").click()
2021-12-08 20:54:01 +03:00
```
```csharp
2022-11-16 20:54:40 +03:00
await page.GetByTestId("directions").ClickAsync();
2022-09-30 21:14:13 +03:00
```
2022-11-11 18:23:00 +03:00
### Locate by CSS or XPath
2022-09-30 21:14:13 +03:00
2022-12-03 08:48:37 +03:00
If you absolutely must use CSS or XPath locators, you can use [`method: Page.locator`] to create a locator that takes a selector describing how to find an element in the page. Playwright supports CSS and XPath selectors, and auto-detects them if you omit `css=` or `xpath=` prefix.
2022-09-30 21:14:13 +03:00
```js
await page.locator('css=button').click();
await page.locator('xpath=//button').click();
await page.locator('button').click();
await page.locator('//button').click();
```
```java
page.locator("css=button").click();
page.locator("xpath=//button").click();
page.locator("button").click();
page.locator("//button").click();
```
```python async
2022-10-03 22:24:26 +03:00
await page.locator("css=button").click()
await page.locator("xpath=//button").click()
2022-09-30 21:14:13 +03:00
2022-10-03 22:24:26 +03:00
await page.locator("button").click()
await page.locator("//button").click()
2022-09-30 21:14:13 +03:00
```
```python sync
2022-10-03 22:24:26 +03:00
page.locator("css=button").click()
page.locator("xpath=//button").click()
2022-09-30 21:14:13 +03:00
2022-10-03 22:24:26 +03:00
page.locator("button").click()
page.locator("//button").click()
2022-09-30 21:14:13 +03:00
```
```csharp
await page.Locator('css=button').ClickAsync();
await page.Locator('xpath=//button').ClickAsync();
await page.Locator('button').ClickAsync();
await page.Locator('//button').ClickAsync();
```
2022-10-27 01:30:22 +03:00
XPath and CSS selectors can be tied to the DOM structure or implementation. These selectors can break when the DOM structure changes. Long CSS or XPath chains below are an example of a **bad practice** that leads to unstable tests:
2022-09-30 21:14:13 +03:00
```js
2022-11-16 20:54:40 +03:00
await page.locator(
'#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input'
).click();
2022-09-30 21:14:13 +03:00
2022-11-16 20:54:40 +03:00
await page
.locator('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input')
.click();
2022-09-30 21:14:13 +03:00
```
```java
2022-11-16 20:54:40 +03:00
page.locator(
"#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input"
).click();
2022-09-30 21:14:13 +03:00
page.locator("//*[@id='tsf']/div[2]/div[1]/div[1]/div/div[2]/input").click();
```
```python async
2022-11-16 20:54:40 +03:00
await page.locator(
"#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input"
).click()
2022-09-30 21:14:13 +03:00
2022-11-16 20:54:40 +03:00
await page.locator('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').click()
2022-09-30 21:14:13 +03:00
```
2021-12-08 20:54:01 +03:00
2022-09-30 21:14:13 +03:00
```python sync
2022-11-16 20:54:40 +03:00
page.locator(
"#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input"
).click()
2022-09-30 21:14:13 +03:00
2022-11-16 20:54:40 +03:00
page.locator('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').click()
2022-09-30 21:14:13 +03:00
```
2021-12-08 20:54:01 +03:00
2022-09-30 21:14:13 +03:00
```csharp
await page.Locator("#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input").ClickAsync();
2021-12-08 20:54:01 +03:00
2022-09-30 21:14:13 +03:00
await page.Locator("//*[@id='tsf']/div[2]/div[1]/div[1]/div/div[2]/input").ClickAsync();
2021-12-08 20:54:01 +03:00
```
2022-11-11 18:23:00 +03:00
:::tip When to use this
2022-12-12 16:48:44 +03:00
CSS and XPath are not recommended as the DOM can often change leading to non resilient tests. Instead, try to come up with a locator that is close to how the user perceives the page such as [role locators ](#locate-by-role ) or [define an explicit testing contract ](#locate-by-test-id ) using test ids.
2022-11-11 18:23:00 +03:00
:::
2022-04-25 22:06:18 +03:00
2022-11-11 18:23:00 +03:00
## Locate in Shadow DOM
2022-04-25 22:06:18 +03:00
2022-11-11 18:23:00 +03:00
All locators in Playwright **by default** work with elements in Shadow DOM. The exceptions are:
- Locating by XPath does not pierce shadow roots.
- [Closed-mode shadow roots ](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow#parameters ) are not supported.
Consider the following example with a custom web component:
```html
< x-details role = button aria-expanded = true aria-controls = inner-details >
< div > Title< / div >
#shadow -root
< div id = inner-details > Details< / div >
< / x-details >
```
You can locate in the same way as if the shadow root was not present at all.
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
To click `<div>Details</div>` :
2022-04-25 22:06:18 +03:00
```js
2022-11-11 18:23:00 +03:00
await page.getByText('Details').click();
2022-04-25 22:06:18 +03:00
```
```java
2022-11-11 18:23:00 +03:00
page.getByText("Details").click();
2022-04-25 22:06:18 +03:00
```
```python async
2022-11-11 18:23:00 +03:00
await page.get_by_text("Details").click()
2022-04-25 22:06:18 +03:00
```
```python sync
2022-11-11 18:23:00 +03:00
page.get_by_text("Details").click()
2022-04-25 22:06:18 +03:00
```
```csharp
2022-11-11 18:23:00 +03:00
await page.GetByText("Details").ClickAsync();
2022-04-25 22:06:18 +03:00
```
2022-11-16 00:13:16 +03:00
```html
< x-details role = button aria-expanded = true aria-controls = inner-details >
< div > Title< / div >
#shadow -root
< div id = inner-details > Details< / div >
< / x-details >
```
2022-11-11 18:23:00 +03:00
To click `<x-details>` :
2022-04-25 22:06:18 +03:00
```js
2022-11-11 18:23:00 +03:00
await page.locator('x-details', { hasText: 'Details' }).click();
2022-04-25 22:06:18 +03:00
```
```java
2022-11-16 20:54:40 +03:00
page.locator("x-details", new Page.LocatorOptions().setHasText("Details"))
.click();
2022-04-25 22:06:18 +03:00
```
```python async
2022-11-11 18:23:00 +03:00
await page.locator("x-details", has_text="Details" ).click()
2022-04-25 22:06:18 +03:00
```
```python sync
2022-11-11 18:23:00 +03:00
page.locator("x-details", has_text="Details" ).click()
2022-04-25 22:06:18 +03:00
```
```csharp
2022-11-16 20:54:40 +03:00
await page
2022-11-30 07:56:18 +03:00
.Locator("x-details", new() { HasText = "Details" })
2022-11-16 20:54:40 +03:00
.ClickAsync();
2022-04-25 22:06:18 +03:00
```
2022-11-16 00:13:16 +03:00
```html
< x-details role = button aria-expanded = true aria-controls = inner-details >
< div > Title< / div >
#shadow -root
< div id = inner-details > Details< / div >
< / x-details >
```
2022-04-25 22:06:18 +03:00
2022-11-11 18:23:00 +03:00
To ensure that `<x-details>` contains the text "Details":
2022-04-25 22:06:18 +03:00
```js
2022-11-11 18:23:00 +03:00
await expect(page.locator('x-details')).toContainText('Details');
2022-04-25 22:06:18 +03:00
```
```java
2022-11-11 18:23:00 +03:00
assertThat(page.locator("x-details")).containsText("Details");
2022-04-25 22:06:18 +03:00
```
```python async
2022-11-11 18:23:00 +03:00
await expect(page.locator("x-details")).to_contain_text("Details")
2022-04-25 22:06:18 +03:00
```
```python sync
2022-11-11 18:23:00 +03:00
expect(page.locator("x-details")).to_contain_text("Details")
2022-04-25 22:06:18 +03:00
```
```csharp
2022-11-11 18:23:00 +03:00
await Expect(page.Locator("x-details")).ToContainTextAsync("Details");
2022-04-25 22:06:18 +03:00
```
2022-11-11 18:23:00 +03:00
## Filtering Locators
2022-04-25 22:06:18 +03:00
2022-11-11 18:23:00 +03:00
Consider the following DOM structure where we want to click on the buy button of the second product card. We have a few options in order to filter the locators to get the right one.
2022-09-30 21:14:13 +03:00
2022-11-16 20:54:40 +03:00
```html card
2022-12-15 00:42:52 +03:00
< ul >
< li >
< h3 > Product 1< / h3 >
< button > Add to cart< / button >
< / li >
< li >
< h3 > Product 2< / h3 >
< button > Add to cart< / button >
< / li >
2022-12-16 14:01:33 +03:00
< / ul >
2022-11-11 18:23:00 +03:00
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
### Filter by text
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
Locators can be filtered by text with the [`method: Locator.filter`] method. It will search for a particular string somewhere inside the element, possibly in a descendant element, case-insensitively. You can also pass a regular expression.
2022-09-30 21:14:13 +03:00
```js
2022-11-16 20:54:40 +03:00
await page
.getByRole('listitem')
2022-11-11 18:23:00 +03:00
.filter({ hasText: 'Product 2' })
2022-11-16 00:13:16 +03:00
.getByRole('button', { name: 'Add to cart' })
2022-11-11 18:23:00 +03:00
.click();
```
2022-10-03 22:24:26 +03:00
2022-11-11 18:23:00 +03:00
```java
2022-11-16 20:54:40 +03:00
page.getByRole(AriaRole.LISTITEM)
2022-11-11 18:23:00 +03:00
.filter(new Locator.FilterOptions().setHasText("Product 2"))
2022-11-16 20:54:40 +03:00
.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Add to cart"))
2022-11-11 18:23:00 +03:00
.click();
2022-09-30 21:14:13 +03:00
```
2022-10-03 22:24:26 +03:00
2022-09-30 21:14:13 +03:00
```python async
2022-11-16 20:54:40 +03:00
await page.get_by_role("listitem").filter(has_text="Product 2").get_by_role(
"button", name="Add to cart"
).click()
2022-09-30 21:14:13 +03:00
```
2022-10-03 22:24:26 +03:00
2022-09-30 21:14:13 +03:00
```python sync
2022-11-16 20:54:40 +03:00
page.get_by_role("listitem").filter(has_text="Product 2").get_by_role(
"button", name="Add to cart"
).click()
2022-11-11 18:23:00 +03:00
```
2022-11-16 20:54:40 +03:00
2022-11-11 18:23:00 +03:00
```csharp
2022-11-16 20:54:40 +03:00
await page
.GetByRole(AriaRole.Listitem)
2022-11-30 07:56:18 +03:00
.Filter(new() { HasText = "Product 2" })
2022-12-16 14:01:33 +03:00
.GetByRole(AriaRole.Button, new() { Name = "Add to cart" })
2022-11-11 18:23:00 +03:00
.ClickAsync();
```
2022-10-03 22:24:26 +03:00
2022-11-11 18:23:00 +03:00
Use a regular expression:
2022-10-03 22:24:26 +03:00
2022-11-11 18:23:00 +03:00
```js
2022-11-16 20:54:40 +03:00
await page
.getByRole('listitem')
2022-11-11 18:23:00 +03:00
.filter({ hasText: /Product 2/ })
2022-11-16 00:13:16 +03:00
.getByRole('button', { name: 'Add to cart' })
2022-11-11 18:23:00 +03:00
.click();
```
2022-10-03 22:24:26 +03:00
2022-11-11 18:23:00 +03:00
```java
2022-11-16 20:54:40 +03:00
page.getByRole(AriaRole.LISTITEM)
.filter(new Locator.FilterOptions()
.setHasText(Pattern.compile("Product 2")))
.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Add to cart"))
2022-11-11 18:23:00 +03:00
.click();
```
```python async
2022-11-16 20:54:40 +03:00
await page.get_by_role("listitem").filter(has_text=re.compile("Product 2")).get_by_role(
"button", name="Add to cart"
).click()
2022-11-11 18:23:00 +03:00
```
```python sync
2022-11-16 20:54:40 +03:00
page.get_by_role("listitem").filter(has_text=re.compile("Product 2")).get_by_role(
"button", name="Add to cart"
).click()
2022-09-30 21:14:13 +03:00
```
2022-10-03 22:24:26 +03:00
2022-11-11 18:23:00 +03:00
```csharp
2022-11-16 20:54:40 +03:00
await page
.GetByRole(AriaRole.Listitem)
2022-11-11 18:23:00 +03:00
.Filter(new() { HasTextRegex = new Regex("Product 2") })
2022-12-16 14:01:33 +03:00
.GetByRole(AriaRole.Button, new() { Name = "Add to cart" })
2022-11-11 18:23:00 +03:00
.ClickAsync();
```
2022-11-16 20:54:40 +03:00
### Filter by another locator
Locators support an option to only select elements that have a descendant matching another locator. You can therefore filter by any other locator such as a [`method: Locator.getByRole`], [`method: Locator.getByTestId`], [`method: Locator.getByText`] etc.
```html card
2022-12-15 00:42:52 +03:00
< ul >
< li >
< h3 > Product 1< / h3 >
< button > Add to cart< / button >
< / li >
< li >
< h3 > Product 2< / h3 >
< button > Add to cart< / button >
< / li >
< / ul >
2022-11-16 00:13:16 +03:00
```
2022-11-11 18:23:00 +03:00
```js
2022-11-16 20:54:40 +03:00
await page
.getByRole('listitem')
2022-11-11 18:23:00 +03:00
.filter({ has: page.getByRole('heading', { name: 'Product 2' })})
2022-11-16 00:13:16 +03:00
.getByRole('button', { name: 'Add to cart' })
2022-11-11 18:23:00 +03:00
.click()
```
2022-11-16 20:54:40 +03:00
2022-09-30 21:14:13 +03:00
```java
2022-11-16 20:54:40 +03:00
page.getByRole(AriaRole.LISTITEM)
.filter(new Locator.FilterOptions()
.setHas(page.GetByRole(AriaRole.HEADING, new Page.GetByRoleOptions()
.setName("Product 2"))))
.getByRole(AriaRole.BUTTON,
2022-12-15 00:42:52 +03:00
new Page.GetByRoleOptions().setName("Add to cart"))
2022-11-11 18:23:00 +03:00
.click()
```
2022-11-16 20:54:40 +03:00
2022-11-11 18:23:00 +03:00
```python async
2022-11-16 20:54:40 +03:00
await page.get_by_role("listitem").filter(
has=page.get_by_role("heading", name="Product 2")
).get_by_role("button", name="Add to cart").click()
2022-11-11 18:23:00 +03:00
```
2022-11-16 20:54:40 +03:00
2022-11-11 18:23:00 +03:00
```python sync
2022-11-16 20:54:40 +03:00
page.get_by_role("listitem").filter(
has=page.get_by_role("heading", name="Product 2")
).get_by_role("button", name="Add to cart").click()
2022-11-11 18:23:00 +03:00
```
2022-11-16 20:54:40 +03:00
2022-11-11 18:23:00 +03:00
```csharp
2022-11-16 20:54:40 +03:00
await page
.GetByRole(AriaRole.Listitem)
.Filter(new() {
2022-12-16 14:01:33 +03:00
Has = page.GetByRole(AriaRole.Heading, new() {
2022-11-30 07:56:18 +03:00
Name = "Product 2"
2022-11-16 20:54:40 +03:00
})
})
2022-12-16 14:01:33 +03:00
.GetByRole(AriaRole.Button, new() { Name = "Add to cart" })
2022-11-11 18:23:00 +03:00
.ClickAsync();
```
2022-10-03 22:24:26 +03:00
2022-11-11 18:23:00 +03:00
We can also assert the product card to make sure there is only one
2022-10-03 22:24:26 +03:00
2022-11-11 18:23:00 +03:00
```js
2022-11-16 20:54:40 +03:00
await expect(page
.getByRole('listitem')
2022-12-15 00:42:52 +03:00
.filter({ has: page.getByText('Product 2') }))
2022-11-11 18:23:00 +03:00
.toHaveCount(1);
```
```java
2022-11-16 20:54:40 +03:00
assertThat(page
.getByRole(AriaRole.LISTITEM)
2022-11-11 18:23:00 +03:00
.filter(new Locator.FilterOptions().setHas(page.getByText("Product 2")))
.hasCount(1);
```
```python async
2022-11-16 20:54:40 +03:00
await expect(
page.get_by_role("listitem").filter(
has=page.get_by_role("heading", name="Product 2")
)
).to_have_count(1)
2022-11-11 18:23:00 +03:00
```
```python sync
2022-11-16 20:54:40 +03:00
expect(
page.get_by_role("listitem").filter(
has=page.get_by_role("heading", name="Product 2")
)
).to_have_count(1)
2022-09-30 21:14:13 +03:00
```
2022-10-03 22:24:26 +03:00
2022-09-30 21:14:13 +03:00
```csharp
2022-11-16 20:54:40 +03:00
await Expect(page
.GetByRole(AriaRole.Listitem)
.Filter(new() {
2022-12-16 14:01:33 +03:00
Has = page.GetByRole(AriaRole.Heading, new() { Name = "Product 2" })
2022-11-16 20:54:40 +03:00
})
2022-11-11 18:23:00 +03:00
.toHaveCountAsync(1);
```
Note that the inner locator is matched starting from the outer one, not from the document root.
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
## Chaining Locators
You can chain methods that create a locator, like [`method: Page.getByText`] or [`method: Locator.getByRole`], to narrow down the search to a particular part of the page.
2022-11-16 00:13:16 +03:00
In this example we first create a locator called product by locating the test id. We then filter by text. We can use the product locator again to get by role of button and click it and then use an assertion to make sure there is only one product with the text "Product 2".
2022-11-11 18:23:00 +03:00
```js
2022-11-16 20:54:40 +03:00
const product = page.getByRole('listitem').filter({ hasText: 'Product 2' });
2022-11-11 18:23:00 +03:00
2022-11-16 20:54:40 +03:00
await product.getByRole('button', { name: 'Add to cart' }).click();
2022-11-11 18:23:00 +03:00
await expect(product).toHaveCount(1);
```
```python async
2022-11-16 20:54:40 +03:00
product = page.get_by_role("listitem").filter(has_text="Product 2")
2022-11-11 18:23:00 +03:00
2022-11-16 00:13:16 +03:00
await product.get_by_role("button", name="Add to cart").click()
2022-11-11 18:23:00 +03:00
```
```python sync
2022-11-16 20:54:40 +03:00
product = page.get_by_role("listitem").filter(has_text="Product 2")
2022-11-11 18:23:00 +03:00
2022-11-16 00:13:16 +03:00
product.get_by_role("button", name="Add to cart").click()
2022-11-11 18:23:00 +03:00
```
```java
2022-11-16 20:54:40 +03:00
Locator product = page
2022-11-17 21:41:25 +03:00
.getByRole(AriaRole.LISTITEM)
2022-11-11 18:23:00 +03:00
.filter(new Locator.FilterOptions().setHasText("Product 2"));
2022-11-16 20:54:40 +03:00
product
.getByRole(AriaRole.BUTTON,
new Locator.GetByRoleOptions().setName("Add to cart"))
2022-11-11 18:23:00 +03:00
.click();
```
```csharp
2022-11-16 20:54:40 +03:00
var product = page
.GetByRole(AriaRole.Listitem)
2022-11-30 07:56:18 +03:00
.Filter(new() { HasText = "Product 2" });
2022-11-11 18:23:00 +03:00
2022-11-16 20:54:40 +03:00
await product
2022-11-30 07:56:18 +03:00
.GetByRole(AriaRole.Button), new() { Name = "Add to cart" })
2022-11-11 18:23:00 +03:00
.ClickAsync();
```
## Lists
### Count items in a list
You can assert locators in order to count the items in a list.
For example, consider the following DOM structure:
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< ul >
< li > apple< / li >
< li > banana< / li >
< li > orange< / li >
< / ul >
```
Use the count assertion to ensure that the list has 3 items.
```js
await expect(page.getByRole('listitem')).toHaveCount(3);
```
```python async
await expect(page.get_by_role("listitem")).to_have_count(3)
```
```python sync
expect(page.get_by_role("listitem")).to_have_count(3)
```
```java
assertThat(page.getByRole(AriaRole.LISTITEM).hasCount(3);
```
```csharp
2022-11-16 20:54:40 +03:00
await Expect(page.GetByRole(AriaRole.Listitem)).ToHaveCountAsync(3);
2022-11-11 18:23:00 +03:00
```
### Assert all text in a list
You can assert locators in order to find all the text in a list.
For example, consider the following DOM structure:
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< ul >
< li > apple< / li >
< li > banana< / li >
< li > orange< / li >
< / ul >
```
Use [`method: LocatorAssertions.toHaveText`] to ensure that the list has the text "apple", "banana" and "orange".
```js
2022-11-16 20:54:40 +03:00
await expect(page
.getByRole('listitem'))
2022-11-11 18:23:00 +03:00
.toHaveText(['apple', 'banana', 'orange']);
```
```python async
await expect(page.get_by_role("listitem")).to_have_text(["apple", "banana", "orange"])
```
```python sync
expect(page.get_by_role("listitem")).to_have_text(["apple", "banana", "orange"])
```
```java
2022-11-16 20:54:40 +03:00
assertThat(page
.getByRole(AriaRole.LISTITEM))
2022-11-11 18:23:00 +03:00
.hasText(new String[] { "apple", "banana", "orange" });
```
```csharp
2022-11-16 20:54:40 +03:00
await Expect(page
.GetByRole(AriaRole.Listitem))
2022-11-11 18:23:00 +03:00
.ToHaveTextAsync(new string[] {"apple", "banana", "orange"});
```
### Get a specific item
There are many ways to get a specific item in a list.
#### Get by text
Use the [`method: Page.getByText`] method to locate an element in a list by it's text content and then click on it.
For example, consider the following DOM structure:
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< ul >
< li > apple< / li >
< li > banana< / li >
< li > orange< / li >
< / ul >
```
Locate an item by it's text content and click it.
```js
2022-11-16 20:54:40 +03:00
await page.getByText('orange').click();
2022-11-11 18:23:00 +03:00
```
```python async
await page.get_by_text("orange").click()
```
```python sync
page.get_by_text("orange").click()
```
```java
2022-11-16 20:54:40 +03:00
page.getByText("orange").click();
2022-11-11 18:23:00 +03:00
```
```csharp
2022-11-16 20:54:40 +03:00
await page.GetByText("orange").ClickAsync();
2022-11-11 18:23:00 +03:00
```
2022-11-16 20:54:40 +03:00
```html card
2022-11-16 00:13:16 +03:00
< ul >
< li > apple< / li >
< li > banana< / li >
< li > orange< / li >
< / ul >
```
2022-11-11 18:23:00 +03:00
#### Filter by text
Use the [`method: Locator.filter`] to locate a specific item in a list.
For example, consider the following DOM structure:
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< ul >
< li > apple< / li >
< li > banana< / li >
< li > orange< / li >
< / ul >
```
Locate an item by the role of "listitem" and then filter by the text of "orange" and then click it.
```js
2022-11-16 20:54:40 +03:00
await page
.getByRole('listitem')
2022-11-11 18:23:00 +03:00
.filter({ hasText: 'orange' })
.click();
```
```python async
await page.get_by_role("listitem").filter(has_text="orange").click()
```
```python sync
page.get_by_role("listitem").filter(has_text="orange").click()
```
```java
page.getByRole(AriaRole.LISTITEM)
.filter(new Locator.FilterOptions().setHasText("orange"))
.click();
```
```csharp
2022-11-16 20:54:40 +03:00
await page
.GetByRole(AriaRole.Listitem)
2022-11-30 07:56:18 +03:00
.Filter(new() { HasText = "orange" })
2022-11-11 18:23:00 +03:00
.ClickAsync();
```
2022-11-16 00:13:16 +03:00
2022-11-11 18:23:00 +03:00
#### Get by test id
Use the [`method: Page.getByTestId`] method to locate an element in a list. You may need to modify the html and add a test id if you don't already have a test id.
For example, consider the following DOM structure:
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< ul >
< li data-testid = 'apple' > apple< / li >
< li data-testid = 'banana' > banana< / li >
< li data-testid = 'orange' > orange< / li >
< / ul >
```
Locate an item by it's test id of "orange" and then click it.
```js
2022-11-16 20:54:40 +03:00
await page.getByTestId('orange').click();
2022-11-11 18:23:00 +03:00
```
```python async
await page.get_by_test_id("orange").click()
```
```python sync
page.get_by_test_id("orange").click()
```
```java
2022-11-16 20:54:40 +03:00
page.getByTestId("orange").click();
2022-11-11 18:23:00 +03:00
```
```csharp
2022-11-16 20:54:40 +03:00
await page.GetByTestId("orange").ClickAsync();
2022-11-16 00:13:16 +03:00
```
2022-11-11 18:23:00 +03:00
#### Get by nth item
If you have a list of identical elements, and the only way to distinguish between them is the order, you can choose a specific element from a list with [`method: Locator.first`], [`method: Locator.last`] or [`method: Locator.nth`].
```js
const banana = await page.getByRole('listitem').nth(1);
```
```python async
banana = await page.get_by_role("listitem").nth(1)
```
```python sync
banana = page.get_by_role("listitem").nth(1)
```
```java
Locator banana = page.getByRole(AriaRole.LISTITEM).nth(1);
```
```csharp
2022-11-16 20:54:40 +03:00
var banana = await page.GetByRole(AriaRole.Listitem).NthAsync(1);
2022-11-11 18:23:00 +03:00
```
However, use this method with caution. Often times, the page might change, and the locator will point to a completely different element from the one you expected. Instead, try to come up with a unique locator that will pass the [strictness criteria ](#strictness ).
### Chaining filters
When you have elements with various similarities, you can use the [`method: Locator.filter`] method to select the right one. You can also chain multiple filters to narrow down the selection.
For example, consider the following DOM structure:
2022-11-16 20:54:40 +03:00
```html card
2022-11-11 18:23:00 +03:00
< ul >
< li >
< div > John< / div >
< div > < button > Say hello< / button > < / div >
< / li >
< li >
< div > Mary< / div >
< div > < button > Say hello< / button > < / div >
< / li >
< li >
< div > John< / div >
< div > < button > Say goodbye< / button > < / div >
< / li >
< li >
< div > Mary< / div >
< div > < button > Say goodbye< / button > < / div >
< / li >
< / ul >
```
To take a screenshot of the row with "Mary" and "Say goodbye":
```js
const rowLocator = page.getByRole('listitem');
await rowLocator
.filter({ hasText: 'Mary' })
.filter({ has: page.getByRole('button', { name: 'Say goodbye' }) })
2022-11-16 20:54:40 +03:00
.screenshot({ path: 'screenshot.png' });
2022-11-11 18:23:00 +03:00
```
```python async
row_locator = page.get_by_role("listitem")
2022-11-16 20:54:40 +03:00
await row_locator
.filter(has_text="Mary")
.filter(has=page.get_by_role("button", name="Say goodbye"))
.screenshot(path="screenshot.png")
2022-11-11 18:23:00 +03:00
```
```python sync
row_locator = page.get_by_role("listitem")
2022-11-16 20:54:40 +03:00
row_locator
.filter(has_text="Mary")
.filter(has=page.get_by_role("button", name="Say goodbye"))
.screenshot(path="screenshot.png")
2022-11-11 18:23:00 +03:00
```
```java
Locator rowLocator = page.getByRole(AriaRole.LISTITEM);
2022-11-16 20:54:40 +03:00
rowLocator
.filter(new Locator.FilterOptions().setHasText("Mary"))
.filter(new Locator.FilterOptions()
.setHas(page.getByRole(
AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Say goodbye"))))
2022-11-11 18:23:00 +03:00
.screenshot(new Page.ScreenshotOptions().setPath("screenshot.png"));
```
```csharp
2022-11-16 20:54:40 +03:00
var rowLocator = page.GetByRole(AriaRole.Listitem);
2022-11-11 18:23:00 +03:00
2022-11-16 20:54:40 +03:00
await rowLocator
2022-11-30 07:56:18 +03:00
.Filter(new() { HasText = "Mary" })
2022-11-16 20:54:40 +03:00
.Filter(new() {
2022-11-30 07:56:18 +03:00
Has = page.GetByRole(AriaRole.Button), new() { Name = "Say goodbye" })
2022-11-16 20:54:40 +03:00
})
2022-11-11 18:23:00 +03:00
.ScreenshotAsync(new() { Path = "screenshot.png" });
```
You should now have a "screenshot.png" file in your project's root directory.
### Rare use cases
2022-12-15 03:42:50 +03:00
#### Do something with each element in the list
Iterate elements:
2022-11-11 18:23:00 +03:00
```js
2022-12-15 03:42:50 +03:00
for (const row of await page.getByRole('listitem').all())
console.log(await row.textContent());
2022-11-11 18:23:00 +03:00
```
```python async
2022-12-15 03:42:50 +03:00
for row in await page.get_by_role("listitem").all():
print(await row.text_content())
2022-11-11 18:23:00 +03:00
```
```python sync
2022-12-15 03:42:50 +03:00
for row in page.get_by_role("listitem").all():
print(row.text_content())
2022-11-11 18:23:00 +03:00
```
```java
2022-12-15 03:42:50 +03:00
for (Locator row : page.getByRole(AriaRole.LISTITEM).all())
System.out.println(row.textContent());
2022-11-11 18:23:00 +03:00
```
```csharp
2022-12-15 03:42:50 +03:00
foreach (var row in await page.GetByRole(AriaRole.Listitem).AllAsync())
Console.WriteLine(await row.TextContentAsync());
2022-11-11 18:23:00 +03:00
```
2022-12-15 03:42:50 +03:00
Iterate using regular for loop:
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
```js
const rows = page.getByRole('listitem');
const count = await rows.count();
2022-10-03 22:24:26 +03:00
for (let i = 0; i < count ; + + i )
2022-11-11 18:23:00 +03:00
console.log(await rows.nth(i).textContent());
```
```python async
rows = page.get_by_role("listitem")
count = await rows.count()
for i in range(count):
print(await rows.nth(i).text_content())
```
```python sync
rows = page.get_by_role("listitem")
count = rows.count()
for i in range(count):
print(rows.nth(i).text_content())
```
```java
Locator rows = page.getByRole(AriaRole.LISTITEM);
int count = rows.count();
for (int i = 0; i < count ; + + i )
System.out.println(rows.nth(i).textContent());
```
```csharp
2022-11-16 20:54:40 +03:00
var rows = page.GetByRole(AriaRole.Listitem);
2022-11-11 18:23:00 +03:00
var count = await rows.CountAsync();
for (int i = 0; i < count ; + + i )
2022-10-03 22:24:26 +03:00
Console.WriteLine(await rows.Nth(i).TextContentAsync());
2022-11-11 18:23:00 +03:00
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
#### Evaluate in the page
The code inside [`method: Locator.evaluateAll`] runs in the page, you can call any DOM apis there.
```js
const rows = page.getByRole('listitem');
2022-11-16 20:54:40 +03:00
const texts = await rows.evaluateAll(
list => list.map(element => element.textContent));
2022-10-03 22:24:26 +03:00
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
```python async
rows = page.get_by_role("listitem")
texts = await rows.evaluate_all("list => list.map(element => element.textContent)")
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
```python sync
rows = page.get_by_role("listitem")
texts = rows.evaluate_all("list => list.map(element => element.textContent)")
```
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
```java
Locator rows = page.getByRole(AriaRole.LISTITEM);
2022-11-16 20:54:40 +03:00
Object texts = rows.evaluateAll(
"list => list.map(element => element.textContent)");
2022-11-11 18:23:00 +03:00
```
```csharp
2022-11-16 20:54:40 +03:00
var rows = page.GetByRole(AriaRole.Listitem);
var texts = await rows.EvaluateAllAsync(
"list => list.map(element => element.textContent)");
2022-11-11 18:23:00 +03:00
```
## Strictness
Locators are strict. This means that all operations on locators that imply
some target DOM element will throw an exception if more than one element matches. For example, the following call throws if there are several buttons in the DOM:
2022-09-30 21:14:13 +03:00
2022-11-11 18:23:00 +03:00
#### Throws an error if more than one
2022-09-30 21:14:13 +03:00
```js
2022-11-11 18:23:00 +03:00
await page.getByRole('button').click();
```
```python async
await page.get_by_role("button").click()
```
```python sync
page.get_by_role("button").click()
2021-12-08 20:54:01 +03:00
```
```java
2022-11-11 18:23:00 +03:00
page.getByRole(AriaRole.BUTTON).click();
```
```csharp
await page.GetByRole(AriaRole.Button).ClickAsync();
```
On the other hand, Playwright understands when you perform a multiple-element operation,
so the following call works perfectly fine when the locator resolves to multiple elements.
#### Works fine with multiple elements
```js
await page.getByRole('button').count();
2021-12-08 20:54:01 +03:00
```
```python async
2022-11-11 18:23:00 +03:00
await page.get_by_role("button").count()
2021-12-08 20:54:01 +03:00
```
```python sync
2022-11-11 18:23:00 +03:00
page.get_by_role("button").count()
```
```java
2022-11-16 20:54:40 +03:00
page.getByRole(AriaRole.BUTTON).count();
2021-12-08 20:54:01 +03:00
```
```csharp
2022-11-16 20:54:40 +03:00
await page.GetByRole(AriaRole.Button).CountAsync();
2021-12-08 20:54:01 +03:00
```
2022-11-11 18:23:00 +03:00
You can explicitly opt-out from strictness check by telling Playwright which element to use when multiple elements match, through [`method: Locator.first`], [`method: Locator.last`], and [`method: Locator.nth`]. These methods are **not recommended** because when your page changes, Playwright may click on an element you did not intend. Instead, follow best practices above to create a locator that uniquely identifies the target element.
2022-12-03 08:48:37 +03:00
## More Locators
For less commonly used locators, look at the [other locators ](./other-locators.md ) guide.