To find an element reliably in Playwright, start with the locator that expresses what the element means to a user—usually getByRole() with an accessible name, or getByLabel() for a form control. Then scope repeated elements to meaningful context and make sure the locator identifies exactly one intended target. Use a test ID when an explicit internal testing contract is more useful than checking the user-facing interface.
What a Playwright locator does
A locator is a query Playwright resolves when you use it. If the DOM changes between uses, Playwright can resolve it again against the current page. The official Playwright locator documentation calls locators “the central piece of Playwright’s auto-waiting and retry-ability.” This makes locators useful across changing page states, but it does not make a vague or incorrect selector meaningful.
For an action such as a click, Playwright expects a single target and waits for the relevant actionability conditions. A reliable locator therefore has two jobs: identify the intended element and let Playwright determine when that element is ready for the action.
Which locator should you use?
| Target or test intent | Good starting point | What it expresses |
|---|---|---|
| Interactive control with a meaningful accessible role and name | getByRole() |
The control’s semantic role and accessible name, as users and assistive technology perceive them. |
| Form control with an associated label | getByLabel() |
The label a user uses to identify the field. |
| Visible non-interactive copy | getByText() |
Text content; exact strings and regular expressions are available, and whitespace is normalized. |
| Input with a meaningful placeholder and no better locator for the test | getByPlaceholder() |
The placeholder attribute. It can locate an input, but it is not a substitute for a proper accessible label in the interface. |
| Image or element whose alternative text or title is the intended target | getByAltText() or getByTitle() |
The relevant alternative-text or title attribute. |
| Deliberate internal test contract | getByTestId() |
A test ID explicitly assigned by the application team; it does not check the user-facing role or name. |
| Structure is itself under test, or no suitable semantic or explicit-contract locator exists | locator() with CSS or XPath |
A structural or implementation-level query, which can couple a test to DOM details. |
Prefer role and name for controls
For buttons, links, and other semantic controls, use the role and the name that identifies the control:
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errors#1 Best Overall
- 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.
await page.getByRole('button', { name: 'Save' }).click();
This tests an interface-facing property: a button with the accessible name “Save.” If the control is missing its role or has the wrong name, a role-and-name locator can expose that problem instead of silently continuing to find it by an internal identifier.
Use labels for form fields
When a field has an associated label, target that label rather than an incidental class or position:
await page.getByLabel('Email').fill('reader@example.com');
Use text, placeholder, alt text, or title when that is the intended signal
Use getByText() when visible copy identifies the content under test, and use getByPlaceholder(), getByAltText(), or getByTitle() when the corresponding attribute is the relevant contract. Prefer a label for a form field when one is available; a placeholder can change independently and is not a replacement for an accessible label.
Rank #2
- 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 test IDs for an explicit internal contract
A test ID is useful when the application deliberately provides a stable hook and the test is not meant to verify the control’s user-facing name or role:
await page.getByTestId('checkout-submit').click();
This can remain stable through copy changes, which is helpful if copy is not part of the test. The trade-off is that a test ID can still match after a visible label or semantic role regresses. If users depend on that interface property, assert it with a role or text locator instead.
Keep CSS and XPath tied to intentional structure
Playwright supports CSS and XPath through page.locator(). Use them when there is no suitable semantic or test-ID locator, or when DOM structure is itself the behavior being tested. Long selector chains based on incidental classes or nesting can fail after a redesign even when the user-facing feature still works. The Playwright best-practices guide provides further guidance on choosing locators.
Rank #3
- 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.
Scope repeated elements until the target is unique
A page may contain several “Add to cart” buttons. Instead of selecting the first matching button on the page, first find the relevant item using meaningful content, then find its button within that item. For example, with a product card represented as a list item:
const card = page
.getByRole('listitem')
.filter({ has: page.getByRole('heading', { name: 'Product 2' }) });
await expect(card).toHaveCount(1);
await card.getByRole('button', { name: 'Add to cart' }).click();
The filter identifies the card containing the “Product 2” heading; the nested button locator is then evaluated relative to that card. The count assertion makes uniqueness an explicit part of the test contract. If the page can legitimately show multiple matching cards, use a more specific heading or another meaningful distinction rather than asserting a false invariant.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Understand strict mode and uniqueness
Actions that imply one target, such as click(), are strict: if the locator matches multiple elements, Playwright reports a strict mode violation rather than arbitrarily choosing one. That failure often indicates the locator needs a meaningful accessible name or better scope.
Rank #4
- 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
- Add a distinguishing role and accessible name, such as
getByRole('button', { name: 'Save changes' }). - If the element is repeated in a dialog, card, or row, locate that container first and search within it.
- Use a filter such as
hasTextorhasto select the container by meaningful content. - If exactly one match is an intended invariant, assert it with
toHaveCount(1).
first(), last(), and nth() select by position. They are appropriate when position is itself the tested behavior or when no better distinction exists; otherwise, a reordered page can make the same locator silently refer to a different element.
Separate locator correctness from waiting
For a click, Playwright checks that the target is unique, visible, stable, able to receive events, and enabled. It waits for these conditions until the configured timeout; if they do not pass, the action fails. See the official actionability documentation for the conditions used by actions.
Auto-waiting helps with transient readiness, such as a control that becomes visible after rendering. It cannot fix a locator that targets the wrong button, matches several controls, or depends on a page state the test never reached. Before increasing a timeout, verify the locator and the expected state.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Best Value
- 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.
Troubleshoot common locator failures
The action times out
- Check the target: confirm the role, name, text, or scope describes the intended element.
- Check the page state: verify that navigation, rendering, or the interaction that reveals the element has completed as expected.
- Check actionability: determine whether the target is visible, stable, unobscured, and enabled. A click can time out if one of these checks never passes.
- Change the timeout only with a reason: a longer wait can be appropriate for a known slow operation, but it does not correct a selector that is semantically wrong.
Playwright reports a strict mode violation
The locator matched more than one element for a single-target operation. Add a distinguishing name, scope the query to a relevant container, or filter that container by meaningful content. Assert a count of one if uniqueness is a requirement; avoid positional selection unless order matters to the test.
A test breaks after a redesign
Inspect whether the locator relies on a CSS class, deep nesting, or another incidental implementation detail. Replace it with a role/name or other meaningful user-facing property when that property matters to the test. If an internal stable hook is the intended contract, ask the application team to provide a deliberate test ID.
The test passes but misses a user-visible regression
Check whether a test ID is keeping the locator stable despite a change to the control’s visible name or semantic role. If users depend on those properties, test them directly with a role or text locator rather than relying solely on the internal ID.
Choose a locator by the contract you want to test
- Role and name: best when the behavior includes what the control is and what users can identify it as.
- Test ID: best when a deliberate internal hook is the contract and copy or role is not the subject of the test.
- CSS or XPath: appropriate when structure itself matters or other locator forms cannot express the target, with the trade-off of greater coupling to implementation.
- Any locator form: must be sufficiently specific for the current page. No syntax is universally reliable without regard to the element and test intent.
Or skip the browser setup
If you need a screenshot rather than an interactive Playwright test, ScreenshotNeo can capture a page with one GET request. Its capture can accept cookie or consent banners and remove known consent platforms, newsletter popups, and chat widgets before taking the shot; these steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with the response indicating the page verdict and billing status. ScreenshotNeo also provides an MCP server with screenshot, page-info, and PDF-capture tools for AI agents.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for request options. The free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots. Sign up for ScreenshotNeo to start with the free allowance.
Quick Recap
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.

