Understand Playwright Selector Types

On This Page What are Playwright Selectors?D

May 21, 2026 · 13 min read · Tool Comparison

Playwright Selectors: Types

While writing with, selectors often feel straightforward at maiden. The problem shows up when a small UI change interruption multiplePlaywright chooser, even though the feature still works. Tests betray, debugging time increases, and self-confidence in automation drops.

Overview

What are Playwright Selectors?

Playwright selectorsare mechanisms used to place and interact with elements on a web page, allowing tryout to target elements based on attributes, textbook, use, or availableness properties.

Types of Playwright Selectors

  • Basic Text Selectors:Locate elements by matching visible text content.
  • Basic CSS Selectors:Use standard CSS syntax to target ingredient by tag, class, ID, or attribute.
  • Selecting Visible Elements:Filter selectors to interact only with ingredient currently visible on the page.
  • Selecting Elements Containing Other Elements:Identify parent elements that incorporate specific child constituent utilise nested selector.
  • Selecting Elements in:Access element within Shadow DOM trees, which are otherwise conceal from standard selectors.
  • Chained Selectors:Combine multiple selectors in succession to just locate nested or complex element construction.

This article explains the different types of Playwright picker and how to use each one to build stable and maintainable tests.

What are Playwright Selectors?

Playwright selector are patterns or expressions habituate to identify and interact with component on a web page during. They act as the bridge between the and the web page ’ s user interface by pinpointing specific elements, such as buttons, links, input fields, or any HTML element, that need to be tested or manipulated.

In Playwright, chooser are often used through the Locator API, which provides powerful method to find, filter, and interact with elements while ensure tests remain stable and leisurely to maintain.

According toAndrey Lushnikov, the creator of Playwright, selectors are designed to remain resilient through UI refactors and miscarry only when real user behavior breaks, which is why they should ponder user interactions rather than DOM construction.

Playwright selectors break on real browsers?

BrowserStack Automate exposes selector failures betimes on real browsers and devices.

Different Types of Playwright Selectors

Here are the different types of Playwright Selectors proficiency:

  • Basic text selectors:This allows you to select an element via its text content.
const submitButton = await page.locator ('text= '' Submit '' ');
  • Basic CSS selectors:These are apply to select elements establish on their CSS properties.
const passwordField = await page.locator ('input [type=password] ');
  • Selecting visible elements:This is utilitarian for selecting elements that are visible on the page.
const visibleDivs = await page.locator ('div: visible ');
  • Selecting elements that carry other elements:Playwright enables based on child component.
const parentDiv = await page.locator ('div & gt; & gt; `` child schoolbook '' ');
  • Selecting component in Shadow DOM:Shadow DOM ingredient can also be selected using Playwright.
const shadowElement = await page.locator ('css=div # shadow-root & gt; & gt; css=span ');
  • Chained selectors:These are used when one chooser need to run relative to the previous one.
const chainedElement = await page.locator ('div.parent & gt; & gt; css=span.child ');

Additionally, Playwright support usage selector engines. This imply you can define your own way of query elements, for representative, ground on a tag name.

Playwright-specific selectors, including text selectors and chain picker, fill in the gaps where CSS and XPath selectors might fall short. They provide an even more powerful way to accurately site and interact with element on a webpage.

Since different browsers and devices may provide component differently, it ’ s important to validate selectors across surround.

cloud platform provides crying access to existent browsers and devices, making it easy to ensure your Playwright selector work reliably everywhere.

Read More:

Understanding Locator API in Playwright

The Locator API is a core characteristic in Playwright that provides a powerful and coherent way to chance and interact with elements on a webpage. Instead of forthwith using raw selectors each clip, Playwright encourages working with, abstractions that represent elements or grouping of elements.

This approach offers several advantages:

  • Reliability:Locators automatically wait for elements to be ready before execute actions, reducing caused by timing number.
  • Reusability:Once define, a locater can be reprocess multiple times across your test code without repeating selector logic.
  • Clarity: Locators make test playscript leisurely to read and maintain by distinctly representing page elements as objects.
  • Rich Functionality:The Locator API back chaining, filtering, and advanced querying, allowing fine-grained control over element selection and interaction.

In essence, the Locator API builds on top of selector, wrapping them in a more full-bodied interface that helps testers compose stable and maintainable mechanization scripts. Understanding how to create and manipulate locators is indispensable for leveraging Playwright ’ s full potential.

Read More:

Key Features of Playwright ’ s Locator API

Below are the core features and capabilities of Playwright ’ s Locator API that make it powerful and reliable for web automation testing.

  • Creating Locators:Locators are created apply the page.locator () method with selectors such as CSS or XPath. Playwright also auto-detects chooser type when prefixes are omitted, simplifying component targeting.
  • Auto-Waiting and Actionability Checks:Before any interaction, Playwright mechanically look for elements to be visible, enabled, and stable. This reduces by ensuring the element is ready for activity, closely mime real user demeanor.
  • Customizable Action Options:Actions like chink and dblclick support option like perspective, timeout, and trial mode for preparedness chit.
  • Flexible Interaction Controls:Interaction methods allow configure mouse buttons, clink counts, hold intervals, and keyboard changer (e.g., Shift, Control) to simulate diverse user inputs.
    Handling Multiple Elements withcount(): The count () method retrovert the number of elements matching a locater, enabling assertions about element quantity and supporting examination regard lists or radical.
  • Advanced Element Targeting:Locators can select elements ground on text, alt textbook, title, or test IDs.
  • Shadow DOM Support:Playwright locators can access elements inside Shadow DOMs by nonremittal, allow testing of encapsulated web components. However, selectors can not pierce shadow boundaries.
  • Filtering and Chaining Locators:Locators can be refined by chaining or filtering based on text, child constituent, or other conditions, enabling accurate selection within complex or nested DOM structures.

Read More:

CSS Selectors in Playwright

With Playwright, developers can leverage to locate and interact with web component:

  • Element Selector:Selects elements ground on the tag name. Example, the below command take all paragraph elements.
await page.locator (' p ');
  • Class Selector:Selects factor based on the class name. Example, the below dictation selects all factor with the classmyClass.
await page.locator ('.myClass ');
  • ID Selector:Selects an factor base on its ID. Example, take the element with the ID myID using the dictation
await page.locator (' # myID ');
  • Attribute Selector:Selects elements found on an attribute and its value. Example, the below command selects all.
await page.locator ('input [type= '' text ''] ');

Read More:

  • Combining Selectors:Combines different selectors for precision. Example, the below command take a button with classmyClassand text & # 8220;Submit“.
await page.locator ('button.myClass: has-text (`` Submit '') ');
  • Visible Pseudo-class:Selects elements that are visible on the page. Example, the below command select all visible div elements.
await page.locator ('div: seeable ');
  • Has Pseudo-class:Selects elements that contain specific other elements. Example, the below command take div constituent control elements with classchildClass.

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

await page.locator ('div: has (.childClass) ');
  • Not Pseudo-class:Selects elements that do not match a precondition. Example, the below command selectsdivelements that do not have classexcludeClass.
await page.locator ('div: not (.excludeClass) ');
  • FirstChild Pseudo-class:Selects the first tyke element. Example, the below bidding take the first child div element.
await page.locator ('div: first-child ');
  • LastChild Pseudo-class:Selects the last child element. Example, the below command selects the last child div element.
await page.locator ('div: last-child ');
  • Shadow DOM Selector:Selects elements in the Shadow DOM. Example, the below command selects span component inside a div with IDshadow-root.
await page.locator ('div # shadow-root & gt; & gt; css=span ');
  • Chained Selectors:Chains selectors for relative search. Example, the below command choose span with class child inside a div with category parent.
await page.locator ('div.parent & gt; & gt; css=span.child ');
  • CSS Equals:Specifies a CSS selector. Example, the below command selects div elements with classmyClass.
await page.locator ('css=div.myClass ');
  • Visible Pseudo-class with Text:Selects visible elements with specific text. Example, the below bidding selects seeable paragraph elements with the text & # 8220;Hello“.
await page.locator (' p: visible: has-text (`` Hello '') ');
  • Nth-match Pseudo-class:Selects the nth matching ingredient. Example, the below command selects the second div with classmyClass.
await page.locator ('div: nth-match (2, .myClass) ');
  • Playwright-specific selector:Playwright selectors provide extra functionality. Example, the below command selects a React component namedMyComponent.
await page.locator ('_react=MyComponent ');
  • Has-text Pseudo-class:Selects elements containing specific text. Example the beloc command, selects paragraph elements containing the textbook & # 8220;Hello“.
await page.locator (' p: has-text (`` Hello '') ');
  • Is Pseudo-class:Matches an element if it matches any of the selectors. Example, the below bidding, selects paragraph elements that have eitherclass1 or class2.
await page.locator (' p: is (.class1, .class2) ');
  • XPath Selector:Used to select elements using XPath expression. Example the below command take div ingredient with grademyClass.
await page.locator ('//div [@ class= '' myClass ''] ');
  • Custom Selector Engine:Allows you to delineate your own selector engine. Example: Define a custom selector to select elements base on a specific data attribute:
// Define your usance chooser locomotive playwright.selectors.register ('data-testid ', {create (theme, quarry) {return root.querySelector (` [data-testid= '' $ {target} ''] `);},}); // Use your custom selector await page.locator ('data-testid=myTestId ');

This representative make a custom picker engine to select elements establish on adata-testiddimension and uses it to withdata-testid= & # 8221; myTestId & # 8221;.

Talk to an Expert

Xpath Selectors in Playwright

In Playwright, offer a flexible way to nail elements on a webpage, beyond just their tag, course, or ID. They allow developers to pilot through the webpage structure and prime ingredient based on a scope of conditions.

  • Tag Selector:You can take all elements of a particular type. For exemplar, you can select all paragraph elements employ
//p
  • Attribute Selector:XPath chooser can find elements with a specific dimension. For model, you can find all div elements with the classmyClass.
//div [@ class= '' myClass '']
  • Text Content Selector:XPath can select ingredient based on their inner text. So, You can find paragraph ingredient that contain exactly the schoolbook & # 8220;Hello& # 8221; using
//p [text () = '' Hello '']
  • Substring Selector:XPath & # 8217; scontains ()purpose can select elements whose text includes a sure substring. For example, you can find paragraph element that contain& # 8220; Hello & # 8221;anywhere in their textbook using
//p [contains (text (), `` Hello '')]
  • :Using XPath, you can find factor in relation to others. For instance, you can take all div elements that directly follow another div using
//div/following-sibling: :div
  • Position Selector:XPath allows selecting elements found on their order in the webpage. For instance, you can select the maiden div factor on the page using
//div[1]

In short, XPath selectors provide a versatile toolkit to navigate and take component on a webpage when using Playwright, often establish handy when CSS selectors might not be enough.

Also Read:

How to Create Locators in Playwright

In Playwright, are habituate as label put on web page elements to find them so as to interact with them. A locater helps you find an element exemplar a button, and gives you singular information about the button that can be used by the Playwright to interact with and automate the said button.

You create a locater use thepage.locator ()part. You surpass a selector into this function, which can be a description based on the element ’ s tag, category, or early attributes.

Here ’ s an example of how to make a locator usingpage.locator ():

const button = page.locator ('button.myButton ');

In this exemplar, You & # 8217; re telling Playwright to find a button with the classmyButtonand label it asbutton.

Once you have a locator, you can ask the Playwright to execute actions with it. For example, you can tell Playwright to click the push like this:

await button.click ();

This is like tell, & # 8220; Playwright, click on the element labeled as & # 8216; button & # 8217;. & # 8221;

Find the figure of elements for a afford Locator

If you want to cognize how many elements match the locator, you can ask Playwright to count them:

const numberOfButtons = await button.count ();

This is like state, & # 8220; Playwright, how many & # 8216; button & # 8217; labels did you happen? & # 8221;

Create New Playwright Locator based on an existing Locator

You can even make new locators found on subsist ones. This is like adding another sticker to the single already there:

const smallButton = button.locator ('.small ');

This is like saying, & # 8220; Playwright, among the elements labeledbutton, find those with the coursesmalland label themsmallButton.”

In little, locators are a simple and powerful way to interact with web page ingredient in Playwright.

Know more about

Best Practices for using Playwright Selectors

When usingplaywright selectors best praxis, it & # 8217; s kind of like you & # 8217; re setting up directions for Playwright to happen its way around a webpage. So, here are a few tips to keep in brain:

  1. Avoid overly specific selectorsthat rely too heavily on a specific construction or attribute values that may vary.
  2. Be mindful of dynamic content:If parts of the webpage change often, like ads or timestamps, make sure not to tie your selectors to those to avoid exclusion and errors.
  3. Prioritize user-visible attributesince it & # 8217; s easier to maintain tests if your selectors are establish on text or other attribute that you can see when you look at the page, sooner than hidden dimension.
  4. Use picker chaining:In Playwright, you can begin with a broad locator and so concatenation more specific 1 onto it. This makes your codification easier to read and your selectors more robust.
  5. Use waitForSelector cautiously:When navigating, it & # 8217; s good to wait for a landmark to demo up before proceeding. But in Playwright, be cautious about utilisewaitForSelectorfor every individual action & # 8211; it might slacken your test down a lot. Instead, use after actions that cause pilotage.
  6. Avoid using indexesin picker because the order of constituent can alter.

Read More:

Why Run Playwright Tests on Real Devices?

Playwright examination often pass in local or brainless environs but fail when break to existent browsers and devices. Differences in rendering, timing, and DOM behavior can affect selector reliability and UI stability, making real-device essay essential.

  • Validate selector behavior across browsers:Playwright selectors reckon on how browser expose the DOM and accessibility attribute. Real-device examine ensures selectors target the right elements across,,, and.
  • Expose timing and interaction issues:Real devices reveal delays caused by actual hardware, browser rendering, and network weather that are often missed in local or fake run.
  • Ensure consistent user experience:Functional success does not guarantee visual correctness. DOM or selector changes can unintentionally impact layout, spacing, or alignment on different browser.

To bridge this gap between local test consequence and real exploiter conditions, provide access to3,500+ real browsers and gimmick combination, allowing Playwright tests to be formalise in environments that closely match how applications are really used.

enables running Playwright tests on real browsers and operating scheme, corroborate selector reliability in production-like conditions. complement this by catching visual regressions make by DOM or selector changes, ensuring UI consistency across environments.

Conclusion

Playwright selectors play a major role in proceed trial stable as the UI evolves. Using the correct selector character reduces flakiness, improves readability, and cuts down upkeep make by small DOM changes.

Selector conduct can still alter across browsers, yet when tests legislate locally. Running Playwright tests on real browsers and devices with helps affirm selector reliability in real user weather and prevents unexpected failure later.

Tags

FAQs

Playwright selectors are methods used to locate and interact with constituent on a web page, using attribute like schoolbook, roles, labels, test IDs, or CSS structure to ensure reliable component targeting.

Role-based picker and examination ID selector are generally the nearly reliable because they are less affected by DOM or styling changes and best contemplate user-facing behavior.

CSS and XPath selectors are tightly coupled to the DOM construction, making tests more fragile when the UI layout or markup changes, even if functionality remains the same.

Yes. Differences in browser rendering, accessibility trees, and timing can affect how selectors adjudicate ingredient, peculiarly in existent browser environments.

Running Playwright tests on existent browsers and devices usehelps validate that selectors behave systematically across environments, reducing outre tests caused by browser-specific difference.

18,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free