Skip to main content

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_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()

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.

https://:3000
<button>Sign in</button>

Locate the element by its role of button with name "Sign in".

page.get_by_role("button", name="Sign in").click()
note

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.

locator = page.get_by_role("button", name="Sign in")

locator.hover()
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.

locator = page.frame_locator("my-frame").get_by_role("button", name="Sign in")

locator.click()