In Playwright selectors are strings, identifiers that allow you to locate and interact with elements on web pages. They are essential for performing tasks such as form filling, web scraping, and end-to-end testing.
Playwright is an open-source automation library that is designed for end-to-end testing, web scraping, and user interface testing. It supports both headless and headed browser modes and offers excellent performance with its fast and easy-to-use API.
Playwright is compatible with multiple browsers, including Chrome, Microsoft Edge (using Chromium), Safari (using WebKit), and Mozilla Firefox. Playwright provides different types of selectors, including CSS selectors, XPath selectors, and text selectors, each with its own advantages and use cases.
TL;DR
- This guide covers different types of selectors, including CSS, XPath, and text selectors, and explains their usage and benefits.
- It also provides best practices for creating reliable and maintainable automation scripts.
Check also:
Top 15 Codeless Automation Testing Tools for QA
- TL;DR
- Getting Started with Playwright
- Locator API in Playwright
- Playwright CSS Selector
- XPath Selectors in Playwright
- Text Selectors in Playwright
- Combining Selectors in Playwright
- Advanced Selectors in Playwright
- Best Practices for Using Selectors in Playwright
- Using Selectors for Automation in Playwright
- Handling Shadow DOM with Selectors in Playwright
- Conclusion
- FAQ: Playwright Selectors and Locators
Getting Started with Playwright
To get started with Playwright, you need to install it and set up a project.
Here is a step-by-step guide:
- Create a new folder for your Playwright project.
- Open the folder in your terminal or command line interface.
- Run the command
npm init -y
to initialize a new Node.js project. - Install Playwright by running the command
npm install playwright
. - Import Playwright and create a new browser instance.
const { chromium } = require('playwright');
(async () => {\
 const browser = await chromium.launch();\
 const page = await browser.newPage();\
 // Your code here\
 await browser.close();\
})();
With Playwright set up, you are ready to start using selectors to interact with web elements. If you are looking for more information about using Playwright, check out our Playwright Cheat Sheet.
Locator API in Playwright
Playwright's Locator API is a central feature for auto-waiting and retry-ability, enabling robust interaction with web page elements. Here are some key points about it:
- Creating Locators: Locators are created using the
page.locator()
method. This method 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 thecss=
orxpath=
prefix. - Actionability Checks: Before performing actions, Playwright performs actionability checks on elements. This includes ensuring the element is visible, enabled, and stable. For example, when clicking an element, Playwright will wait for it to become clickable.
- Options for Actions: When performing actions like
click
ordblclick
, you can specify various options:
position
: The x and y coordinates relative to the element's padding box's top-left corner.timeout
: The maximum time in milliseconds to wait for the action to complete. It defaults to 30 seconds, but you can pass 0 to disable the timeout.trial
: When set to true, the method performs actionability checks without executing the action. This is useful for ensuring an element is ready for interaction.
- Click and Double Click: The
click
method clicks an element, and you can specify options like mouse button, click count, delay between mousedown and mouseup, and modifiers (e.g., Shift, Control). Thedblclick
method works similarly but performs a double-click. - Counting Elements: The
count
method returns the number of elements matching a given selector, helping in assertions to check the number of specific elements on a page. - Locating by Text, Alt Text, Title, and Test ID: You can locate elements based on their text content, alt text, title attribute, or test IDs. This is especially useful for finding non-interactive elements like
div
,span
,p
, etc., and for images and elements with specific titles or testing IDs. - Shadow DOM: Locators in Playwright work with elements in the Shadow DOM by default, with the exception that locating by XPath does not pierce shadow roots.
- Filtering Locators: You can filter locators by text, presence of child elements, or other criteria. This is useful when you need to select a specific item from a list or a group of elements.
The Locator API in Playwright is designed to mimic user interactions as closely as possible, making it a powerful tool for writing reliable and maintainable tests. For more detailed information, you can refer to the official Playwright documentation on Locators and Locator methods.
Playwright CSS Selector
CSS selectors, a staple in web development, are utilized extensively in Playwright for pinpointing elements within web pages. These selectors act as strings that represent different elements based on their attributes, classes, or IDs.
Playwright CSS selectors, akin to those in regular CSS, are enhanced for web automation, allowing for precise element identification. They are capable of matching any element containing specified attributes or classes, and their syntax is very similar to traditional CSS. This includes complex selectors like pseudo-classes, which are an experimental CSS feature in Playwright.
Additionally, Playwright supports attribute selector operators and can resolve selectors that turn multiple spaces into one, ensuring that whitespace is always normalized.
- Basic CSS Selector Usage:
-
Playwright can locate elements using standard CSS syntax.
await page.locator('css=button').click();
- Piercing Shadow DOM:
- CSS selectors in Playwright can pierce open shadow DOMs, allowing access to shadow-root elements.
- Custom Pseudo-classes:
- Playwright introduces pseudo-classes like
:visible
,:has-text()
,:has()
,:is()
,:nth-match()
, and more. :visible
targets only visible elements.
await page.locator('button:visible').click();
-
:has-text()
matches elements containing specified text, useful for case-insensitive, whitespace-trimmed substring matching.await page.locator('article:has-text("Playwright")').click();
- Matching by Text:
-
:text()
pseudo-class matches the smallest element containing specified text.await page.locator('#nav-bar :text("Home")').click();
-
:text-is()
matches the smallest element with exact text.await page.locator('#nav-bar :text-is("Home")').click();
-
:text-matches()
matches elements with text content matching a JavaScript-like regex.await page.locator('#nav-bar :text-matches("reg?ex", "i")').click();
- Elements That Contain Other Elements:
-
The
:has()
pseudo-class is an experimental CSS feature in Playwright. It returns an element if it contains other elements specified by the selectors.await page.locator('article:has(div.promo)').textContent();
- Matching Elements Based on Layout:
- Playwright's layout pseudo-classes like
:right-of()
,:left-of()
,:above()
,:below()
, and:near()
can be used to select elements based on their spatial relationship to other elements.
await page.locator('input:right-of(:text("Password"))').fill('value');
- Pick N-th Match from the Query Result:
- The
:nth-match()
pseudo-class selects a specific instance of an element among several matches.
await page.locator(':nth-match(:text("Buy"), 3)').click();
These features make CSS selectors in Playwright a powerful tool for web automation, allowing precise targeting of elements not only based on their attributes and text content but also their visibility, containment, and relative positioning.
This versatility is particularly beneficial in complex web applications where standard selectors might not suffice.
XPath Selectors in Playwright
XPath selectors offer another robust method for element location in Playwright. Unlike CSS selectors, XPath selectors are based on the XML structure of a web page. They allow you to find elements based on their position, attributes, and other criteria, navigating through the DOM with precision. This is particularly useful when CSS selectors might fall short, such as in complex layouts or when needing to find the smallest element containing the specified text.
XPath in Playwright also supports custom selector engines, providing flexibility in selecting elements that may not be easily accessible through CSS.
You can use BugBug's No-code Online XPath Builder for creating robust selectors.
- Selecting an Element by XPath:
You can select elements using their XPath, which allows for a more flexible and precise targeting based on the structure of the DOM.
const elementByXPath = await page.$x('//div[@class="example"]');
- Evaluating XPath Expressions:
Playwright can evaluate XPath expressions and return the matching elements. $x is a shorthand method provided by Playwright for this purpose.
const elements = await page.$x('//button[contains(text(), "Submit")]');
- Using Axes in XPath:
XPath's axes methods can be utilized to navigate the DOM in various ways, such as selecting a parent, sibling, or child elements relative to a current node.
const siblingElement = await page.$x('//input[@id="username"]/following-sibling::input');
- XPath with Conditional Expressions:
XPath selectors can include conditions to match elements with specific attributes or text content.
const elementWithCondition = await page.$x('//div[@data-status="active" and text()="Active"]');
- Selecting Elements Inside Shadow DOM:
While XPath doesn't natively pierce Shadow DOM, Playwright allows targeting elements inside shadow roots using a combination of CSS and XPath selectors.
Check also our comparison: XPath vs CSS Selector
Text Selectors in Playwright
Text selectors in Playwright focus on locating elements based on visible text content. These selectors are ideal for targeting elements that contain specific text nodes or for searching for a text node with exact content.
The syntax of text selectors in Playwright is straightforward, allowing you to directly specify the text to be matched, which may be escaped with single or double quotes. This feature is particularly useful in web automation scripts where identifying elements by their text content is more practical than using attributes or XPath.
Combining Selectors in Playwright
Playwright also supports the combination of multiple selectors, a feature that enhances the precision of element selection. By chaining selectors together, you can create more specific queries. This might involve combining CSS and XPath selectors, or using multiple selectors of the same type to pinpoint an element based on several criteria.
For instance, you can select an element based on its layout and relative position to other elements, or combine attribute selectors with text selectors to find an element containing specified text somewhere inside it. Chained selectors resolve to the element that matches all the conditions in the chain, offering a powerful tool for complex web automation tasks.
The Locator API in Playwright simplifies the process of interacting with web elements by providing a more stable and powerful way to query and manipulate them. It's particularly useful in dynamic web applications where elements might change state or content, and in scenarios where complex interactions are required.
Advanced Selectors in Playwright
In addition to CSS selectors and XPath selectors, Playwright supports a range of advanced selectors that offer even more flexibility. These advanced selectors include React selectors, accessibility selectors, CSS pseudo-classes, and XPath functions.
Here is an overview of some advanced selectors in Playwright:
- React Selectors: Used to identify elements in React applications.
- Accessibility Selectors: Used to locate elements based on their accessibility properties.
- CSS Pseudo-classes: Used to select elements based on various states or conditions.
- XPath Functions: Used to perform complex queries using XPath functions.
Playwright's advanced selectors allow you to fine-tune your element selection and handle more complex scenarios.
Best Practices for Using Selectors in Playwright
To make the most of Playwright selectors, it's important to follow best practices. Here are some tips to keep in mind:
- Use unique identifiers: Whenever possible, rely on unique identifiers like IDs or data attributes to locate elements.
- Avoid unstable selectors: Selectors that are prone to change, such as those based on positional relationships, should be avoided.
- Update selectors regularly: Periodically review and update your selectors to account for any changes in the website's structure.
By following these best practices, you can ensure the stability and reliability of your automation scripts.
Using Selectors for Automation in Playwright
Playwright selectors are invaluable for automation tasks such as form filling, web scraping, and end-to-end testing. Let's explore a few examples of how selectors can be used for automation in Playwright:
Form Filling
This script demonstrates the basic functionality of Playwright for browser automation, specifically launching a browser, navigating pages, and interacting with web elements. It's important to note that this script does not navigate to a specific URL, so if you intend to use it for a particular website, you'll need to add a line to navigate to that website using page.goto('your-website-url').
const { chromium } = require('playwright');
(async () => {\
 const browser = await chromium.launch();\
 const page = await browser.newPage();
 const usernameInput = await page.locator('#username');\
 await usernameInput.fill('johndoe');
 const passwordInput = await page.locator('#password');\
 await passwordInput.fill('password123');
 await browser.close();\
})();
Web Scraping
The provided Playwright script demonstrates how to extract and print the text content of all hyperlink 'a' elements on a web page using Playwright's automation capabilities.
The script starts by importing the Chromium module from Playwright, then launches a Chromium browser instance and opens a new page. It uses the $$eval
function to select all hyperlink elements on the page and maps their text content to an array. This array is then iterated over, and the text content of each link is printed to the console.
Finally, the script closes the browser page.
 const { chromium } = require('playwright');
(async () => {\
 const browser = await chromium.launch();\
 const page = await browser.newPage();
 const links = await page.$$eval('a', (links) => links.map((link) => link.textContent));
 for (const linkText of links) {\
  console.log(linkText);\
 }
 await page.close();\
})();
End-to-End Testing
The provided code is a Playwright script for automating a basic login process on a web page using the Chromium browser.
The script begins by importing the Playwright module and launching the Chromium browser. It then opens a new browser page.
Next, the script locates the username and password input fields on the page by their respective IDs #username
and #password
and fills them with predefined credentials 'johndoe' and 'password123'.
After filling in the login credentials, the script locates and clicks the login button #loginButton
. It then waits to confirm that the logout button #logoutButton
is visible, which is likely used as an indication of a successful login.
Finally, the script closes the browser page. This automation script is a basic example of how Playwright can be used for automating login procedures in web applications.
const { chromium } = require('playwright');
(async () => {\
 const browser = await chromium.launch();\
 const page = await browser.newPage();
 const usernameInput = await page.locator('#username');\
 await usernameInput.fill('johndoe');
 const passwordInput = await page.locator('#password');\
 await passwordInput.fill('password123');
 const loginButton = await page.locator('#loginButton');\
 await loginButton.click();
 const logoutButton = await page.locator('#logoutButton');\
 await expect(logoutButton).toBeVisible();
 await page.close();\
})();
Handling Shadow DOM with Selectors in Playwright
Playwright's CSS and text engines can pierce through the Shadow DOM, allowing you to interact with elements as if the shadow root was not present. This capability simplifies the process of selecting and manipulating elements within the Shadow DOM.
For locating elements in the Shadow DOM, Playwright's standard locators like page.locator()
, page.getByText()
, and others can be used directly. For example, if you have a custom web component with a shadow root and want to click a specific element inside it, you can use page.getByText('Details').click()
to target an element with the text 'Details'. Similarly, to click a custom element like <x-details>
, you can use page.locator('x-details', { hasText: 'Details' }).click()
.
Playwright also supports advanced selector strategies, such as filtering locators by text, child/descendant elements, or using layout pseudo-classes like :right-of()
, :left-of()
, :above()
, :below()
, and :near()
to target elements based on their layout relative to other elements. These pseudo-classes are particularly useful when elements lack distinct attributes or text content, allowing you to specify their relative positions for more precise selection.
Additionally, Playwright provides specialized locators for React and Vue applications, identified by the _react
and _vue
prefixes, respectively. These locators allow you to find elements based on component names and property values, which can be especially handy in modern web applications using these frameworks.
It's important to note that while XPath can be used in Playwright, it does not pierce shadow roots, and its usage is generally discouraged in favor of more stable, user-visible locators.
Conclusion
Playwright selectors are a powerful tool for automating web testing, web scraping, and user interface testing tasks. By leveraging CSS selectors, XPath selectors, and text selectors, you can precisely locate and interact with elements on web pages.
By following best practices and utilizing the advanced features of Playwright selectors, you can streamline your automation scripts and improve their reliability. Start using Playwright selectors today and unlock the full potential of your automation endeavors.
Remember to regularly update your selectors, use unique identifiers, and explore the various options available in Playwright's selector engine to make your automation scripts more efficient and robust.
Happy (automated) testing!
Read also Top Playwright Alternatives.
FAQ: Playwright Selectors and Locators
What selectors are supported by Playwright?
Playwright supports a diverse array of selectors to select elements, catering to different web automation needs. These include:
- CSS Selectors: Target elements based on their CSS attributes. Playwright's CSS selectors work like regular CSS but are enhanced for automation.
- XPath Selectors: Useful for complex DOM structures, XPath selectors can navigate and find elements based on their XML path.
- Text Selectors: Locate elements containing specified text somewhere inside, ideal for finding text nodes or elements with exact text content.
- Playwright-specific Selectors: These include selectors like data-test-id for targeting elements in a way that's specific to Playwright's framework.
- React Selectors: Selectors designed for React applications, allowing interaction with React components.
- Attribute Selectors: These selectors use attribute selector operators and can match any element based on its attributes.
- Chained Selectors: Combine multiple selectors, like CSS and XPath, to resolve more complex selection scenarios.
- Layout Selectors: Depend on the layout and relative position of elements, using things like bounding client rect for calculations.
How do you select an element in Playwright?
Selecting an element in Playwright typically involves using a string that represents one of the selectors in the list above. For instance:
- CSS Selector:
page.$('.className')
selects elements based on class. - XPath Selector:
page.$x('//div')
uses XPath syntax to find elements. - Text Selector:
page.$('text=Example')
finds an element containing the specified text. - Combined Selectors: Chain selectors like
page.$('div.className > span')
to target a specific element within a different element.
What is a Playwright locator or selector?
A Playwright locator or selector is a string-based tool used to select elements in web automation scripts. Selectors are the means by which Playwright identifies elements to interact with, whether for clicking, reading content, or inputting data. They can be simple, like text selectors, or more complex, like chained selectors combining CSS and XPath.
Can we use XPath in Playwright?
Yes, XPath is a fully supported selector in the Playwright framework. It can be used to perform precise element selection, especially in scenarios where CSS selectors might fall short. XPath selectors in Playwright can navigate the DOM using various axes, predicates, and functions, and are useful for targeting elements based on their structure and content, including text nodes and attributes. For example, page.$x('//button[@id="submit"]')
would locate a button with the ID "submit".