---
title: "Find elements the way people do · Agent Wranglers"
url: https://agentwranglers.se/playbook/testing/end-to-end-and-browser-tests/stable-selectors
updated: 2026-10-20
licence: "All rights reserved"
---

# Find elements the way people do

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Required
- Chapter: [End-to-end and browser tests](https://agentwranglers.se/playbook/testing/end-to-end-and-browser-tests)
- Rule: Find elements by their role, label or visible text. Never by CSS classes or page structure that change with the design.
- How: Use queries such as `getByRole`, `getByLabel` and `getByText` in Playwright or Testing Library. When nothing visible fits, add a `data-testid` on purpose. These queries also prove that buttons and fields have accessible names.
- Check: Search the browser tests for CSS and XPath selectors, such as `locator('.`, `locator('#`, `locator('//` or `xpath=`. There are none, or each has a comment explaining why.

Example:

```js
// Bad: breaks when the design changes
await page.locator('div.card > .btn-primary:nth-child(2)').click();

// Good: survives a redesign and checks the accessible name
await page.getByRole('button', { name: 'Add to cart' }).click();
```

```python
# Playwright for Python
page.get_by_role("button", name="Add to cart").click()
```

```java
// Playwright for Java
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Add to cart")).click();
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers testing playbook: https://agentwranglers.se/playbook/testing/end-to-end-and-browser-tests/stable-selectors`.

- Previous: [Cover only the critical journeys](https://agentwranglers.se/playbook/testing/end-to-end-and-browser-tests/critical-journeys)
- Next: [Wait for the page to be ready instead of sleeping](https://agentwranglers.se/playbook/testing/end-to-end-and-browser-tests/no-sleeps)
- [End-to-end and browser tests](https://agentwranglers.se/playbook/testing/end-to-end-and-browser-tests)
