--- id: locators title: "Locators" --- [Locator]s are the central piece of Playwright's auto-waiting and retry-ability. In a nutshell, locators represent a way to find element(s) on the page at any moment. ### Quick Guide These are the recommended built in locators. - [`method: Page.getByRole`](#locate-by-role) to locate by explicit and implicit accessibility attributes. - [`method: Page.getByText`](#locate-by-text) to locate by text content. - [`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. - [`method: Page.getByAltText`](#locate-by-alt-text) to locate an element, usually image, by its text alternative. - [`method: Page.getByTitle`](#locate-by-title) to locate an element by its title attribute. - [`method: Page.getByTestId`](#locate-by-test-id) to locate an element based on its `data-testid` attribute (other attributes can be configured). ```js 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(); ``` ```java page.getByLabel("User Name").fill("John"); page.getByLabel("Password").fill("secret-password"); page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in")) .click(); assertThat(page.getByText("Welcome, John!")).isVisible(); ``` ```python async 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() ``` ```python sync 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() ``` ```csharp await page.GetByLabel("User Name").FillAsync("John"); await page.GetByLabel("Password").FillAsync("secret-password"); await page.GetByRole(AriaRole.Button, new() { Name = "Sign in" }).ClickAsync(); await Expect(page.GetByText("Welcome, John!")).ToBeVisibleAsync(); ``` ## Locating elements 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`]. For example, consider the following DOM structure. ```html card ``` Locate the element by its role of `button` with name "Sign in". ```js await page.getByRole('button', { name: 'Sign in' }).click(); ``` ```java page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in")) .click(); ``` ```python async await page.get_by_role("button", name="Sign in").click() ``` ```python sync page.get_by_role("button", name="Sign in").click() ``` ```csharp await page.GetByRole(AriaRole.Button, new() { Name = "Sign in" }).ClickAsync(); ``` :::tip Use the [code generator](./codegen.md) to generate a locator, and then edit it as you'd like. ::: 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. ```js const locator = page.getByRole('button', { name: 'Sign in' }) await locator.hover(); await locator.click(); ``` ```java Locator locator = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in")) locator.hover(); locator.click(); ``` ```python async locator = page.get_by_role("button", name="Sign in") await locator.hover() await locator.click() ``` ```python sync locator = page.get_by_role("button", name="Sign in") locator.hover() locator.click() ``` ```csharp var locator = page.GetByRole(AriaRole.Button, new() { Name = "Sign in" }) await locator.HoverAsync(); await locator.ClickAsync(); ``` 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 const locator = page .frameLocator('#my-frame') .getByRole('button', { name: 'Sign in' }); await locator.click(); ``` ```java Locator locator = page .frameLocator("#my-frame") .getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in")); locator.click(); ``` ```python async locator = page.frame_locator("#my-frame").get_by_role("button", name="Sign in") await locator.click() ``` ```python sync locator = page.frame_locator("my-frame").get_by_role("button", name="Sign in") locator.click() ``` ```csharp var locator = page .FrameLocator("#my-frame") .GetByRole(AriaRole.Button), new() { Name = "Sign in" }); await locator.ClickAsync(); ``` ### 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. ```html card

Sign up


``` You can locate each element by it's implicit role: ```js await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible() await page.getByRole('checkbox', { name: 'Subscribe' }).check(); await page.getByRole('button', { name: /submit/i }).click(); ``` ```python async await expect(page.get_by_role("heading", name="Sign up")).to_be_visible() await page.get_by_role("checkbox", name="Subscribe").check() await page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click() ``` ```python sync expect(page.get_by_role("heading", name="Sign up")).to_be_visible() page.get_by_role("checkbox", name="Subscribe").check() page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click() ``` ```java assertThat(page .getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Sign up"))) .isVisible(); page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setName("Subscribe")) .check(); page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName( Pattern.compile("submit", Pattern.CASE_INSENSITIVE))) .click(); ``` ```csharp await Expect(page .GetByRole(AriaRole.Heading, new() { Name = "Sign up" })) .ToBeVisibleAsync(); await page .GetByRole(AriaRole.Checkbox, new() { Name = "Subscribe" }) .CheckAsync(); await page .GetByRole(AriaRole.Button, new() { NameRegex = new Regex("submit", RegexOptions.IgnoreCase) }) .ClickAsync(); ``` 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 ` ``` You can locate the element by it's test id: ```js await page.getByTestId('directions').click(); ``` ```java page.getByTestId("directions").click(); ``` ```python async await page.get_by_test_id("directions").click() ``` ```python sync page.get_by_test_id("directions").click() ``` ```csharp await page.GetByTestId("directions").ClickAsync(); ``` :::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). ::: #### Set a custom test id attribute 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`]. 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; ``` ```js tab=js-ts // playwright.config.ts import type { PlaywrightTestConfig } from '@playwright/test'; const config: PlaywrightTestConfig = { use: { testIdAttribute: 'data-pw' } }; export default config; ``` ```java playwright.selectors().setTestIdAttribute("data-pw"); ``` ```python async playwright.selectors.set_test_id_attribute("data-pw") ``` ```python sync playwright.selectors.set_test_id_attribute("data-pw") ``` ```csharp playwright.Selectors.SetTestIdAttribute("data-pw"); ``` In your html you can now use `data-pw` as your test id instead of the default `data-testid`. ```html card ``` And then locate the element as you would normally do: ```js await page.getByTestId('directions').click(); ``` ```java page.getByTestId("directions").click(); ``` ```python async await page.get_by_test_id("directions").click() ``` ```python sync page.get_by_test_id("directions").click() ``` ```csharp await page.GetByTestId("directions").ClickAsync(); ``` ### Locate by CSS or XPath 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. ```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 await page.locator("css=button").click() await page.locator("xpath=//button").click() await page.locator("button").click() await page.locator("//button").click() ``` ```python sync page.locator("css=button").click() page.locator("xpath=//button").click() page.locator("button").click() page.locator("//button").click() ``` ```csharp await page.Locator('css=button').ClickAsync(); await page.Locator('xpath=//button').ClickAsync(); await page.Locator('button').ClickAsync(); await page.Locator('//button').ClickAsync(); ``` 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: ```js await page.locator( '#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input' ).click(); await page .locator('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input') .click(); ``` ```java page.locator( "#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input" ).click(); page.locator("//*[@id='tsf']/div[2]/div[1]/div[1]/div/div[2]/input").click(); ``` ```python async await page.locator( "#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input" ).click() await page.locator('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').click() ``` ```python sync page.locator( "#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input" ).click() page.locator('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').click() ``` ```csharp await page.Locator("#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input").ClickAsync(); await page.Locator("//*[@id='tsf']/div[2]/div[1]/div[1]/div/div[2]/input").ClickAsync(); ``` :::tip When to use this 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. ::: ## Locate in Shadow DOM 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
Title
#shadow-root
Details
``` You can locate in the same way as if the shadow root was not present at all. To click `
Details
`: ```js await page.getByText('Details').click(); ``` ```java page.getByText("Details").click(); ``` ```python async await page.get_by_text("Details").click() ``` ```python sync page.get_by_text("Details").click() ``` ```csharp await page.GetByText("Details").ClickAsync(); ``` ```html
Title
#shadow-root
Details
``` To click ``: ```js await page.locator('x-details', { hasText: 'Details' }).click(); ``` ```java page.locator("x-details", new Page.LocatorOptions().setHasText("Details")) .click(); ``` ```python async await page.locator("x-details", has_text="Details" ).click() ``` ```python sync page.locator("x-details", has_text="Details" ).click() ``` ```csharp await page .Locator("x-details", new() { HasText = "Details" }) .ClickAsync(); ``` ```html
Title
#shadow-root
Details
``` To ensure that `` contains the text "Details": ```js await expect(page.locator('x-details')).toContainText('Details'); ``` ```java assertThat(page.locator("x-details")).containsText("Details"); ``` ```python async await expect(page.locator("x-details")).to_contain_text("Details") ``` ```python sync expect(page.locator("x-details")).to_contain_text("Details") ``` ```csharp await Expect(page.Locator("x-details")).ToContainTextAsync("Details"); ``` ## Filtering Locators 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. ```html card