--- id: locators title: "Locators" --- ## Introduction [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(); ``` :::note 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 its 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 its 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(); ``` :::note[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 title="playwright.config.ts" import { defineConfig } from '@playwright/test'; export default defineConfig({ use: { testIdAttribute: 'data-pw' } }); ``` ```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(); ``` :::note[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 ``` ### Filter by text 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. ```js await page .getByRole('listitem') .filter({ hasText: 'Product 2' }) .getByRole('button', { name: 'Add to cart' }) .click(); ``` ```java page.getByRole(AriaRole.LISTITEM) .filter(new Locator.FilterOptions().setHasText("Product 2")) .getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Add to cart")) .click(); ``` ```python async await page.get_by_role("listitem").filter(has_text="Product 2").get_by_role( "button", name="Add to cart" ).click() ``` ```python sync page.get_by_role("listitem").filter(has_text="Product 2").get_by_role( "button", name="Add to cart" ).click() ``` ```csharp await page .GetByRole(AriaRole.Listitem) .Filter(new() { HasText = "Product 2" }) .GetByRole(AriaRole.Button, new() { Name = "Add to cart" }) .ClickAsync(); ``` Use a regular expression: ```js await page .getByRole('listitem') .filter({ hasText: /Product 2/ }) .getByRole('button', { name: 'Add to cart' }) .click(); ``` ```java page.getByRole(AriaRole.LISTITEM) .filter(new Locator.FilterOptions() .setHasText(Pattern.compile("Product 2"))) .getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Add to cart")) .click(); ``` ```python async await page.get_by_role("listitem").filter(has_text=re.compile("Product 2")).get_by_role( "button", name="Add to cart" ).click() ``` ```python sync page.get_by_role("listitem").filter(has_text=re.compile("Product 2")).get_by_role( "button", name="Add to cart" ).click() ``` ```csharp await page .GetByRole(AriaRole.Listitem) .Filter(new() { HasTextRegex = new Regex("Product 2") }) .GetByRole(AriaRole.Button, new() { Name = "Add to cart" }) .ClickAsync(); ``` ### Filter by not having text Alternatively, filter by **not having** text: ```js // 5 in-stock items await expect(page.getByRole('listitem').filter({ hasNotText: 'Out of stock' })).toHaveCount(5); ``` ```java // 5 in-stock items assertThat(page.getByRole(AriaRole.LISTITEM) .filter(new Locator.FilterOptions().setHasNotText("Out of stock"))) .hasCount(5); ``` ```python async # 5 in-stock items await expect(page.get_by_role("listitem").filter(has_not_text="Out of stock")).to_have_count(5) ``` ```python sync # 5 in-stock items expect(page.get_by_role("listitem").filter(has_not_text="Out of stock")).to_have_count(5) ``` ```csharp // 5 in-stock items await Expect(Page.getByRole(AriaRole.Listitem).Filter(new() { HasNotText = "Out of stock" })) .ToHaveCountAsync(5); ``` ### Filter by child/descendant Locators support an option to only select elements that have or have not 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 ``` ```js await page .getByRole('listitem') .filter({ has: page.getByRole('heading', { name: 'Product 2' }) }) .getByRole('button', { name: 'Add to cart' }) .click(); ``` ```java page.getByRole(AriaRole.LISTITEM) .filter(new Locator.FilterOptions() .setHas(page.GetByRole(AriaRole.HEADING, new Page.GetByRoleOptions() .setName("Product 2")))) .getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Add to cart")) .click(); ``` ```python async 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() ``` ```python sync page.get_by_role("listitem").filter( has=page.get_by_role("heading", name="Product 2") ).get_by_role("button", name="Add to cart").click() ``` ```csharp await page .GetByRole(AriaRole.Listitem) .Filter(new() { Has = page.GetByRole(AriaRole.Heading, new() { Name = "Product 2" }) }) .GetByRole(AriaRole.Button, new() { Name = "Add to cart" }) .ClickAsync(); ``` We can also assert the product card to make sure there is only one: ```js await expect(page .getByRole('listitem') .filter({ has: page.getByRole('heading', { name: 'Product 2' }) })) .toHaveCount(1); ``` ```java assertThat(page .getByRole(AriaRole.LISTITEM) .filter(new Locator.FilterOptions() .setHas(page.GetByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Product 2"))))) .hasCount(1); ``` ```python async await expect( page.get_by_role("listitem").filter( has=page.get_by_role("heading", name="Product 2") ) ).to_have_count(1) ``` ```python sync expect( page.get_by_role("listitem").filter( has=page.get_by_role("heading", name="Product 2") ) ).to_have_count(1) ``` ```csharp await Expect(Page .GetByRole(AriaRole.Listitem) .Filter(new() { Has = page.GetByRole(AriaRole.Heading, new() { Name = "Product 2" }) })) .ToHaveCountAsync(1); ``` The filtering locator **must be relative** to the original locator and is queried starting with the original locator match, not the document root. Therefore, the following will not work, because the filtering locator starts matching from the `