Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use page.locator('button') to find elements with CSS in Playwright; the equivalent explicit form is page.locator('css=button'). Playwright auto-detects CSS when you omit the prefix. The locator is resolved when an action runs, so it can target the current matching element after a page re-render. For reliable tests, keep selectors specific and make sure a single-element action identifies exactly the element you intend.

Find an element with a CSS selector

Call page.locator() with a CSS selector, then use a locator action such as click() or fill(). You do not need a separate query step to retrieve an element before interacting with it.

await page.locator('button').click();
await page.locator('.submit-button').click();
await page.locator('#login').fill('alice@example.com');
await page.locator('input[name="email"]').fill('alice@example.com');

Both page.locator('button') and page.locator('css=button') mean a CSS locator. The prefix can be useful when a selector’s type might otherwise be unclear, especially if the same code also uses XPath:

const cssButton = page.locator('css=button');
const xpathButton = page.locator('xpath=//button');

A locator describes how to find an element; Playwright resolves it when an operation needs it. This is useful on pages that re-render: an action can work with the current matching element rather than depending on an earlier, potentially stale element reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Build selectors for the element you mean

CSS works well when the page’s structure or a deliberate attribute is the contract your test should verify. Start with the shortest selector that reliably distinguishes the target.

Tags, classes, and IDs

A tag selector matches by element type, a class selector by class, and an ID selector by ID. These are straightforward, but a broad selector such as button may match several elements.

await page.locator('button').click();
await page.locator('.submit-button').click();
await page.locator('#login').fill('alice@example.com');

Attributes and form controls

Attribute selectors can express a more purposeful target, such as a particular input name or control type:

await page.locator('input[name="email"]').fill('alice@example.com');
await page.locator('form#login input[type="password"]').fill('secret');

If your team owns a stable test attribute, it can act as an explicit selector contract:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.locator('[data-testid="sign-in"]').click();

Descendants and direct children

A space selects a matching descendant at any depth. The > combinator selects only a direct child. Use the latter when that structural relationship is intentional.

await page.locator('form#login input[type="password"]').fill('secret');
await page.locator('nav > a').first().click();

Long chains that reproduce every wrapper in the current markup are usually fragile: a layout change can break a test even when the user-facing behavior is unchanged. Prefer a short selector scoped to a meaningful container when that gives the intended target.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Use Playwright’s CSS selector extensions

Playwright extends CSS with selectors that can narrow a match by visibility, text, containment, or position. These can make a selector more expressive, but they do not remove the need to check that the final locator targets the intended element.

Visibility and text

:visible narrows a CSS match to visible elements. :has-text() narrows by text contained in an element:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.locator('button:visible').click();
await page.locator('article:has-text("Playwright")').click();

Text-based CSS extensions may still match more than one element. If the text alone is not distinctive, scope the selector to the relevant region or use a user-facing locator with a clearer name.

Containment and alternatives

:has() selects an element based on a matching descendant, while :is() groups alternatives:

await page.locator('section:has(button)').locator('button').click();
await page.locator('button:is(.primary, .confirm)').click();

These selectors help express containment or a set of acceptable classes without expanding into a long chain. In the containment example, the section selector may match several sections, and the nested button locator may still match multiple buttons; refine the scope if necessary.

Positional matching

:nth-match() selects a match by its one-based position:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
await page.locator(':nth-match(button, 3)').click();

Position-based selection is appropriate only when position is part of the test’s intended contract. If order changes as the page evolves, it may select the wrong control without expressing that the control’s meaning changed.

Open shadow DOM

Playwright CSS selectors pierce open shadow DOM. This can let a CSS locator reach matching elements inside open shadow roots. Do not assume that a selector has identified the right control merely because it crosses that boundary; still check scope and uniqueness.

Choose CSS or a user-facing locator

Playwright recommends user-facing locators such as getByRole(), getByText(), getByLabel(), getByPlaceholder(), getByAltText(), getByTitle(), and getByTestId(). They can make tests more resilient when styling classes, nesting, or layout change, and often communicate the user’s view of the page more clearly.

// A semantic locator describes the control and its accessible name.
await page.getByRole('button', { name: 'Sign in' }).click();

// CSS is suitable when this test attribute is an agreed, stable contract.
await page.locator('[data-testid="sign-in"]').click();
  • Meaning: role and label locators describe what a user can perceive; CSS describes markup, attributes, or structure.
  • Resilience: semantic locators often tolerate styling and layout changes better than selectors tied to implementation details.
  • Uniqueness: either kind of locator must identify the intended target for a single-element action.
  • Ownership: a data-testid or another agreed attribute can be a stable team-owned contract, if the application maintains it.

Use CSS when the structure or attribute is the point of the test, or when it is the clearest available way to express the target. Prefer a user-facing locator when it states the intent more directly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle multiple matches and strictness

Single-target actions such as click() are strict: if a locator resolves to several matching elements, Playwright throws a strictness violation rather than choosing one silently. Multi-element operations such as count() can be used to inspect the number of matches.

const buttons = page.locator('button');
await expect(buttons).toHaveCount(3);

That assertion is useful when the expected number of elements is itself part of the test. If the goal is to click one button, narrow the selector to the intended control instead of accepting an ambiguous match.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
await page.locator('form#checkout button[type="submit"]').click();

await page.locator('li')
  .filter({ hasText: 'Mary' })
  .getByRole('button', { name: 'Say hello' })
  .click();

You can choose a match with first(), last(), or nth(). Use these only when position is deliberately meaningful; page changes can alter ordering and make a positional choice target a different element.

const buttons = page.locator('button');
await expect(buttons).toHaveCount(3);
await buttons.nth(1).click(); // Zero-based position: the second button.

Practical workflow for reliable CSS locators

  1. Start with meaning. If a role, label, or other user-facing locator states the intent clearly, use it. Otherwise identify a stable CSS hook or structure the test is meant to exercise.
  2. Keep the selector focused. Prefer a concise selector, scoped to a meaningful form or container, over a chain that mirrors every wrapper.
  3. Check the match set. Use count() or an expectation such as toHaveCount() when the number of matches matters; refine the selector before a single-target action if it is ambiguous.
  4. Use extensions deliberately. Add visibility, text, containment, or positional matching only when that condition is part of how the intended target is identified.
  5. Re-evaluate maintenance. If a selector breaks after a styling or markup change, ask whether the test should use a more semantic locator or a stable, team-owned test attribute.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common CSS locator failures

Strictness violation on click or fill

Cause: the selector matches multiple elements, but the action expects one. Fix: narrow it with a distinctive attribute, a meaningful container, or a user-facing locator. Use first(), last(), or nth() only if the position is intentional.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The locator finds no element

Cause: the selector may not match the current markup, or a page re-render may have changed the relevant structure. Fix: check the tag, attribute value, class, and parent-child relationship; confirm that the intended element is present before acting. If the selector depends on several wrappers, simplify it or anchor it to a stable container.

The selector matches the wrong control

Cause: a broad tag, class, text, or positional selector is not distinctive enough. Fix: express the intended form, section, attribute, or user-facing name. Do not rely on position unless order is a tested requirement.

A selector breaks after a visual redesign

Cause: it encodes styling or layout details that changed even though the control’s purpose did not. Fix: consider a role or label locator, or agree on a stable test attribute with the application team.

A text or visibility extension still matches more than once

Cause: the condition narrows the set but does not make it unique. Fix: scope the locator to a relevant region or add a more distinguishing condition, then verify the match set before a single-element action.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Performance, reliability, and cost considerations

The documented guidance here does not establish a speed advantage for CSS selectors over other Playwright locator types, so choose based on clarity and resilience rather than an assumed benchmark. Playwright’s locator model resolves a target when an action runs and supports auto-waiting and retry-ability; a concise selector with a clear contract is generally easier to maintain than an opaque positional chain.

There is no separate price for using CSS locators established here. Reliability depends more directly on whether the selector remains tied to the intended element as the page changes, and whether ambiguity is surfaced rather than hidden by an arbitrary positional choice.

Or skip the browser setup

If your task is to capture a page image rather than interact with its elements in a Playwright test, ScreenshotNeo offers a website screenshot API and MCP server. Its one-request API can return a screenshot or PDF; the cURL example below saves a WebP capture of Stripe. See the ScreenshotNeo API documentation for request options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

Does Playwright require the `css=` prefix?

No. Playwright auto-detects CSS when you pass a selector such as `button` without a prefix.

Are Playwright CSS selectors zero-based or one-based with `nth()`?

`locator.nth()` uses a zero-based index, so `nth(1)` selects the second match.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.