Locators
Introduction
Locators 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.
- page.get_by_role() to locate by explicit and implicit accessibility attributes.
- page.get_by_text() to locate by text content.
- page.get_by_label() to locate a form control by associated label's text.
- page.get_by_placeholder() to locate an input by placeholder.
- page.get_by_alt_text() to locate an element, usually image, by its text alternative.
- page.get_by_title() to locate an element by its title attribute.
- page.get_by_test_id() to locate an element based on its
data-testidattribute (other attributes can be configured).
- Sync
- Async
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()
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()
Locating elements
Playwright comes with multiple built-in locators. To make tests resilient, we recommend prioritizing user-facing attributes and explicit contracts such as page.get_by_role().
For example, consider the following DOM structure.
<button>Sign in</button>
Locate the element by its role of button with name "Sign in".
- Sync
- Async
page.get_by_role("button", name="Sign in").click()
await page.get_by_role("button", name="Sign in").click()
Use the code generator 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.
- Sync
- Async
locator = page.get_by_role("button", name="Sign in")
locator.hover()
locator.click()
locator = page.get_by_role("button", name="Sign in")
await locator.hover()
await locator.click()
Note that all methods that create a locator, such as page.get_by_label(), are also available on the Locator and FrameLocator classes, so you can chain them and iteratively narrow down your locator.
- Sync
- Async
locator = page.frame_locator("my-frame").get_by_role("button", name="Sign in")
locator.click()
locator =