Locators in Playwright
Locators are a powerful tool that can be used to find elements on a page with great precision. Playwright provides a variety of locators that can be used to find elements by their role, text, label, placeholder, alt text, title, or data-testid attribute.
Playwright locators are technology-agnostic, which means they can locate elements in web pages, web applications, and native applications. In contrast, Selenium locators are based solely on the Document Object Model (DOM) and can only locate elements in web pages. Finally, Cypress locators are specific to the Cypress framework and can only be used to locate elements in web pages being tested with Cypress.
Playwright locators are highly versatile and can locate elements using various properties such as text, id, class, and XPath. In contrast, Selenium locators are less versatile, only locating elements through limited properties like id, class, and name. Meanwhile, Cypress locators share Playwright’s versatility, allowing them to locate elements through a range of properties.
Locators provide a way to find elements on a page with built-in auto-waiting and retry-ability. When a locator is used for an action, an up-to-date DOM element is located on the page. There are several methods to create a locator, such as page.getByLabel(), which can be used with Locator and FrameLocator classes. This allows for chaining and iterative refinement of the locator to obtain more precise results.
page.getByRole()
to locate by explicit and implicit accessibility attributes.
await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
await page.getByRole('checkbox', { name: 'Subscribe' }).check();
await page.getByRole('button', { name: /submit/i }).click();
When locating an element by role, it is best to include the accessible name as well. This allows the locator to pinpoint the exact element. To make the entire expression case-insensitive, use the letter “i”. For example, /submit/i
would match "Submit".
page.getByText()
to locate by text content.
await expect(page.getByText('Welcome, John')).toBeVisible();
await expect(page.getByText('Welcome, John', { exact: true })).toBeVisible();
await expect(page.getByText(/welcome, [A-Za-z]+$/i)).toBeVisible();
This locator can find elements that match a substring, exact string, or regular expression. When matching by text, it always normalizes whitespace, even with an exact match. For example, it reduces multiple spaces to one, converts line breaks to spaces, and ignores leading and trailing whitespace. It is recommended to use text locators to find non-interactive elements like div
, span
, and p
.
page.getByLabel()
to locate a form control by associated label's text.
await page.getByLabel('Password').fill('secret');
page.getByPlaceholder()
to locate an input by placeholder.
await page.getByPlaceholder("[name@example.com](<name@example.com>)")
.fill("[playwright@microsoft.com](<playwright@microsoft.com>)");
Use this locator to locate form elements that do not have labels but have placeholder text.
page.getByAltText()
to locate an element, usually image, by its text alternative.
await page.getByAltText('playwright logo').click();
page.getByTitle()
to locate an element by its title attribute.
await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
page.getByTestId()
function is used to locate an element based on its data-testid
attribute. However, it can be configured in the test configuration.
await page.getByTestId('directions').click();
Using a getByTestId
is recommended when an element cannot be located by its role or text.
page.locator()
is used to create a locator that describes how to find an element on the page.
await page.locator('//button').click();
await page.locator('button').click();
locator.or
The method in Playwright is used to create a locator that matches an element if it matches either of the two locators passed as arguments. For example, the following code will find the first button on the page that has the text “Submit”:
const button = await page.locator('button').or('button[text="Submit"]');
locator.filter (hasNot, hasNotText
The locator.filter()
method in Playwright is used to filter the results of a locator. The hasNot()
and hasNotText()
methods are used to filter the results to exclude elements that have the specified attribute or text content.
const productList = await page.locator('ul.product-list');
const product = await productList.filter(hasText('iPhone 13 Pro'));
const addCartButton = await product.locator('button', { name: 'Add to cart' });
await addCartButton.click();
The hasText()
method filters the results to include only the list item element that contains the text "iPhone 13 Pro". This code will work on any page that has a list of products, where the list item element contains the text "iPhone 13 Pro" and a button element with the name "Add to cart".
locator.and
The locator.and()
method in Playwright is used to create a locator that matches an element if it matches both of the locators passed as arguments.
const button = page.getByRole('button').and(page.getByTitle('Subscribe'))
will find the first button element on the page that has the role "button" and the title "Subscribe". The getByRole()
method is used to find all button elements on the page. The and()
method is then used to filter the results to only include button elements that have the title "Subscribe".
My recent publication compiled a comprehensive collection of 100 similar typescript programs. Each program not only elucidates essential Typescript concepts and expounds upon the significance of test automation but also provides practical guidance on its implementation using Playwright. This resource will undoubtedly be valuable if you look deeper into similar topics.