Locators
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(role, **kwargs) to locate by explicit and implicit accessibility attributes.
- page.get_by_text(text, **kwargs) to locate by text content.
- page.get_by_label(text, **kwargs) to locate a form control by associated label's text.
- page.get_by_placeholder(text, **kwargs) to locate an input by placeholder.
- page.get_by_alt_text(text, **kwargs) to locate an element, usually image, by its text alternative.
- page.get_by_title(text, **kwargs) to locate an element by its title.
- page.get_by_test_id(test_id) to locate an element based on its
data-testid
attribute (other attribute 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()
Every time locator is used for some action, up-to-date DOM element is located in the page. So in the snippet below, underlying DOM element is going to be located twice, 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_text("Submit")
locator.hover()
locator.click()
locator = page.get_by_text("Submit")
await locator.hover()
await locator.click()
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 given selector. For example, the following call throws if there are several buttons in the DOM:
- Sync
- Async
page.get_by_role("button").click()
await page.get_by_role("button").click()
On the other hand, Playwright understands when you perform a multiple-element operation, so the following call works perfectly fine when locator resolves to multiple elements.
- Sync
- Async
page.get_by_role("button").count()
await page.get_by_role("button").count()
You can explicitly opt-out from strictness check by telling Playwright which element to use when multiple element match, through locator.first, locator.last, and locator.nth(index). These methods are not recommended because when your page changes, Playwright may click on an element you did not intend. Instead, follow best practices below to create a locator that uniquely identifies the target element.
Locating elements
Playwright comes with multiple built-in ways to create a locator. To make tests resilient, we recommend prioritizing user-facing attributes and explicit contracts, and provide dedicated methods for them, such as page.get_by_text(text, **kwargs). It is often convenient to use the code generator to generate a locator, and then edit it as you'd like.
- Sync
- Async
page.get_by_text("Log in").click()
await page.get_by_text("Log in").click()
If you absolutely must use CSS or XPath locators, you can use page.locator(selector, **kwargs) to create a locator that takes a selector describing how to find an element in the page.
Note that all methods that create a locator, such as page.get_by_label(text, **kwargs), 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_text("Submit")
locator.click()
locator = page.frame_locator("#my-frame").get_by_text("Submit")
await locator.click()
Locate based on accessible attributes
The page.get_by_role(role, **kwargs) 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 locator pinpoints the exact element.
- Sync
- Async
page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
page.get_by_role("checkbox", checked=True, name="Check me").check()
await page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
await page.get_by_role("checkbox", checked=True, name="Check me").check()
Role locators follow W3C specifications for ARIA role, ARIA attributes and accessible name.
Note that role locators do not replace accessibility audits and conformance tests, but rather give early feedback about the ARIA guidelines.
Locate by label text
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 page.get_by_label(text, **kwargs).
For example, consider the following DOM structure.
<label for="password">Password:</label><input type="password" id="password">
You can fill the input after locating it by the label text:
- Sync
- Async
page.get_by_label("Password").fill("secret")
await page.get_by_label("Password").fill("secret")
Locate by placeholder text
Inputs may have a placeholder attribute to hint to the user what value should be entered. You can locate such an input using page.get_by_placeholder(text, **kwargs).
For example, consider the following DOM structure.
<input id="email" name="email" type="email" placeholder="name@example.com">
You can fill the input after locating it by the placeholder text:
- Sync
- Async
page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")
await page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")
Locate by text
The easiest way to find an element is to look for the text it contains. You can match by a substring, exact string, or a regular expression when using page.get_by_text(text, **kwargs).
- Sync
- Async
page.get_by_text("Log in").click()
page.get_by_text("Log in", exact=True).click()
page.get_by_text(re.compile("Log in", re.IGNORECASE)).click()
await page.get_by_text("Log in").click()
await page.get_by_text("Log in", exact=True).click()
await page.get_by_text(re.compile("Log in", re.IGNORECASE)).click()
You can also filter by text when locating in some other way, for example find a particular item in the list.
- Sync
- Async
page.get_by_test_id("product-item").filter(has_text="Playwright Book").click()
await page.get_by_test_id("product-item").filter(has_text="Playwright Book").click()
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.
Locate by alt text
All images should have an alt
attribute that describes the image. You can locate an image based on the text alternative using page.get_by_alt_text(text, **kwargs).
For example, consider the following DOM structure.
<img alt="playwright logo" src="/playwright-logo.png" />
You can click on the image after locating it by the text alternative:
- Sync
- Async
page.get_by_alt_text("playwright logo").click()
await page.get_by_alt_text("playwright logo").click()
Locate by title
Locate an element with a matching title attribute using page.get_by_title(text, **kwargs).
For example, consider the following DOM structure.
<span title='Issues count'>25 issues</span>
You can check the issues count after locating it by the title text:
- Sync
- Async
expect(page.get_by_title("Issues count")).to_have_text("25 issues")
await expect(page.get_by_title("Issues count")).to_have_text("25 issues")
Define explicit contract and use a data-testid attribute
User-facing attributes like text or accessible name can change over time. In this case it is convenient to define explicit test ids and query them with page.get_by_test_id(test_id).
<button data-testid="directions">Itinéraire</button>
- Sync
- Async
page.get_by_test_id("directions").click()
await page.get_by_test_id("directions").click()
By default, page.get_by_test_id(test_id) will locate elements based on the data-testid
attribute, but you can configure it in your test config or calling selectors.set_test_id_attribute(attribute_name).
Locate in a subtree
You can chain methods that create a locator, like page.get_by_text(text, **kwargs) or locator.get_by_role(role, **kwargs), to narrow down the search to a particular part of the page.
For example, consider the following DOM structure:
<div data-testid='product-card'>
<span>Product 1</span>
<button>Buy</button>
</div>
<div data-testid='product-card'>
<span>Product 2</span>
<button>Buy</button>
</div>
For example, we can first find a product card that contains text "Product 2", and then click the button in this specific product card.
- Sync
- Async
product = page.get_by_test_id("product-card").filter(has_text="Product 2")
product.get_by_text("Buy").click()
product = page.get_by_test_id("product-card").filter(has_text="Product 2")
await product.getByText("Buy").click()
Locate by CSS or XPath selector
Playwright supports CSS and XPath selectors, and auto-detects them if you omit css=
or xpath=
prefix. Use page.locator(selector, **kwargs) for this:
- Sync
- Async
page.locator("css=button").click()
page.locator("xpath=//button").click()
page.locator("button").click()
page.locator("//button").click()
await page.locator("css=button").click()
await page.locator("xpath=//button").click()
await page.locator("button").click()
await page.locator("//button").click()
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:
- Sync
- Async
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()
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()
Instead, try to come up with a locator that is close to how user perceives the page or define an explicit testing contract.
Locate elements that contain other elements
Filter by text
Locator can be optionally filtered by text. 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.
- Sync
- Async
page.get_by_test_id("product-card").filter(has_text="Product 3").click()
page.get_by_test_id("product-card").filter(has_text=re.compile("Product 3")).click()
await page.get_by_test_id("product-card").filter(has_text="Product 3").click()
await page.get_by_test_id("product-card").filter(has_text=re.compile("Product 3")).click()
Filter by another locator
Locators support an option to only select elements that have a descendant matching another locator.
- Sync
- Async
page.get_by_role("section").filter(has=page.get_by_test_id("subscribe-button"))
page.get_by_role("section").filter(has=page.get_by_test_id("subscribe-button"))
Note that inner locator is matched starting from the outer one, not from the document root.
Augment an existing locator
You can filter an existing locator by text or another one, using locator.filter(**kwargs) method, possibly chaining it multiple times.
- Sync
- Async
row_locator = page.locator("tr")
# ...
row_locator
.filter(has_text="text in column 1")
.filter(has=page.get_by_role("button", name="column 2 button"))
.screenshot()
row_locator = page.locator("tr")
# ...
await row_locator
.filter(has_text="text in column 1")
.filter(has=page.get_by_role("button", name="column 2 button"))
.screenshot()
Locate elements 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 are not supported.
Consider the following example with a custom web component:
<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.
Click
<div>Details</div>
- Sync
- Async
page.get_by_text("Details").click()
await page.get_by_text("Details").click()
Click
<x-details>
- Sync
- Async
page.locator("x-details", has_text="Details" ).click()
await page.locator("x-details", has_text="Details" ).click()
Ensure that
<x-details>
contains text "Details"- Sync
- Async
expect(page.locator("x-details")).to_contain_text("Details")
await expect(page.locator("x-details")).to_contain_text("Details")
Lists
You can also use locators to work with the element lists.
- Sync
- Async
# Locate elements, this locator points to a list.
rows = page.get_by_role("listitem")
# Pattern 1: use locator methods to calculate text on the whole list.
texts = rows.all_text_contents()
# Pattern 2: do something with each element in the list.
count = rows.count()
for i in range(count):
print(rows.nth(i).text_content())
# Pattern 3: resolve locator to elements on page and map them to their text content.
# Note: the code inside evaluateAll runs in page, you can call any DOM apis there.
texts = rows.evaluate_all("list => list.map(element => element.textContent)")
# Locate elements, this locator points to a list.
rows = page.get_by_role("listitem")
# Pattern 1: use locator methods to calculate text on the whole list.
texts = await rows.all_text_contents()
# Pattern 2: do something with each element in the list.
count = await rows.count()
for i in range(count):
print(await rows.nth(i).text_content())
# Pattern 3: resolve locator to elements on page and map them to their text content.
# Note: the code inside evaluateAll runs in page, you can call any DOM apis there.
texts = await rows.evaluate_all("list => list.map(element => element.textContent)")
Picking specific element from a list
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 locator.first, locator.last or locator.nth(index).
For example, to click the third item in the list of products:
- Sync
- Async
page.get_by_test_id("product-card").nth(3).click()
await page.get_by_test_id("product-card").nth(3).click()
However, use these methods with caution. Often times, the page might change, and 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.