In Playwright, start with what a person can identify: use getByRole() and an accessible name for interactive controls, getByLabel() for labeled form fields, and getByText() for non-interactive content. When a page repeats the same control, first scope the locator to the right row or card; then identify the control inside it. This makes the target clearer than relying on a long CSS or XPath selector or an arbitrary position.
Choose a locator that matches the element’s purpose
Playwright describes locators as central to its auto-waiting and retry behavior. A locator expresses how a test identifies an element; the choice also determines which changes the test tolerates and what user-facing behavior it checks. The official guidance is in the Playwright locator guide.
| Page element or testing need | Preferred locator | What it expresses |
|---|---|---|
| Button, link, checkbox, heading, or other semantic element | getByRole(role, { name }) |
The element’s role and accessible name—the way users and assistive technology can identify it. |
| Form field with an associated label | getByLabel(label) |
The field’s label. |
| Visible, non-interactive text such as a status message | getByText(text) |
The text displayed on the page. |
| Field without a label but with a meaningful placeholder | getByPlaceholder(text) |
The placeholder text. |
| Image identified by alternative text | getByAltText(text) |
The image’s alternative text. |
| Element intentionally exposed as a test hook | getByTestId(id) |
An explicit testing contract, using data-testid by default. |
| Element requiring a CSS or XPath selector | locator(selector) |
A selector over the page’s implementation. |
Interactive controls: use role and accessible name
For a control a user acts on, a role locator is a strong default. For example, page.getByRole('button', { name: 'Sign in' }) says both what kind of element the test expects and how it is identified. It can expose a mismatch in role or accessible name that a class-based selector would not catch.
Names can be refined when necessary. For instance, page.getByRole('button', { name: 'Save', exact: true }) requests an exact name match. Use a meaningful name that reflects the control rather than selecting an unrelated piece of text nearby.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC 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 & 11#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.
Form fields: prefer labels
Use page.getByLabel('Password') when the input has a label. If it genuinely has no label but does have a useful placeholder, page.getByPlaceholder('Search products') is an option. A placeholder is not a substitute for an accessible label in the application itself; choosing a locator does not repair the page’s accessibility.
Visible content: use text when text is the target
For a non-interactive message or paragraph, use page.getByText('Payment received'). Text matching normalizes whitespace; use the exact-matching option when the test needs the complete text to match. If the target is interactive, prefer its role and accessible name rather than using text alone, which could match a label or other nearby content instead of the control.
Make repeated elements unambiguous by scoping them
A page may contain many identical buttons—for example, an “Add to cart” button in every product card. Identify the right container first, then find the intended control within it. Playwright’s locator composition and filtering are covered in its best-practices guide.
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.
const product = page.getByRole('listitem').filter({ hasText: 'Product 2' });
const addButton = product.getByRole('button', { name: 'Add to cart' });
await addButton.click();
The filter narrows the list items to the one containing “Product 2.” The subsequent role locator is evaluated within that matched container. This is more resilient than clicking the second matching button and communicates which product the test means.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
If the container is better identified by a child element than by text, use a filter with a locator for that child. Keep the scope tied to a meaningful feature of the intended item, and ensure the resulting locator still identifies one target.
Use test IDs when an explicit testing contract is the right choice
getByTestId('checkout-button') is useful when user-facing role, name, or text does not identify the target well, or when the team deliberately wants a stable hook independent of copy. By default, Playwright looks for data-testid; the test ID attribute can be configured.
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.
This trades some user-facing meaning for an explicit test contract. A test ID can remain stable when copy changes, but it will not verify that the element has the expected accessible role or name. If accessibility semantics are part of what the test should protect, use a role locator or add a separate assertion for those semantics.
Use CSS and XPath selectively
Playwright supports CSS and XPath through page.locator(). They can be appropriate when the target has no useful semantic locator or test hook, or when a test specifically needs to inspect an implementation detail. Avoid selectors that depend on long chains of ancestors, transient classes, or position in the DOM when a role, label, text, or test ID expresses the intended target more directly.
Implementation-coupled selectors can stop matching after a redesign even when the user-facing behavior remains unchanged. The other locators documentation describes alternatives and selector options.
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
Make single-target actions unique
Actions such as click() are strict: if a locator matches multiple elements, Playwright reports a strictness error rather than silently choosing one. Fix the locator by refining its role or name, filtering it, or scoping it to the right container.
first(), last(), and nth(index) are available, but they encode a position, not the identity of the intended element. Use them only when order itself is meaningful and stable. If a list changes, an index can still select an element while selecting the wrong item.
Understand what locator actions wait for
For a click, Playwright waits for the target to be uniquely matched and to pass its actionability checks: it must be visible, stable, able to receive events, and enabled. If a required check does not pass before the timeout, the action times out. These checks help synchronize a test with the page; they do not prove that the locator identifies the element the test intended. See Playwright’s auto-waiting and actionability documentation.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →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.
Do not treat an arbitrary delay as a fix for a locator problem. First check whether the intended element exists, whether it is visible and enabled, whether another element obscures it, and whether the locator matches exactly one target. A locator that uniquely identifies the wrong button can still pass actionability checks.
Inspect pages and review generated locators
Playwright’s code generation can inspect a page and propose locators. Its best-practices guidance says it prioritizes role, text, and test IDs. Treat generated code as a starting point: confirm that it describes the intended element, is unique for the action, and remains meaningful if the page contains repeated controls.
Troubleshoot common locator failures
| Symptom | Likely cause | What to do |
|---|---|---|
| Strictness error on a click | The locator matches more than one element. | Refine the role or accessible name, filter by identifying text or a child locator, or scope to the correct row or card. |
| Action times out | A required actionability check did not pass, or the target is absent or incorrectly identified. | Check presence, uniqueness, visibility, stability, whether the target receives events, and whether it is enabled. Fix the underlying state or locator rather than adding an arbitrary wait. |
| Locator breaks after a redesign | The selector depends on a class, ancestry, or other implementation detail that changed. | Prefer a user-facing role, label, or text when appropriate, or add an intentional test ID contract. |
| A text locator finds the wrong element | The text occurs outside the intended control or in more than one place. | For an interactive target, use its role and accessible name; if controls repeat, scope to the right container. |
nth() selects the wrong list item |
The list order changed while the positional selector remained valid. | Identify the item by its content or stable test contract, then locate the control within it. |
Or skip the browser setup
If you need an image or PDF of a rendered page rather than a locator in a Playwright test, ScreenshotNeo is a website screenshot API and MCP server. A single GET request can return a PNG, JPEG, WebP, or PDF. Its capture flow accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers indicate 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.
For a one-call capture, create an API key and replace YOUR_API_KEY below. The example saves the response body as a WebP file; consult the ScreenshotNeo API documentation for request options and response details.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo includes 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000. Sign up for free.
Frequently Asked Questions
Can I change Playwright’s default test ID attribute?
Yes. Playwright uses data-testid by default, and the test ID attribute can be configured.
Does a passing click mean my locator chose the right element?
No. Actionability checks establish that the matched target is ready for the action; the test still needs a locator that identifies the intended element.
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.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →




