Glossary · UI automation
Locator
Also called: locators, element locator, element locators
Definition
The query a UI test uses to find an element on the page, such as a role and name, a test id, a CSS selector or an XPath expression.
A locator is how a test tells the browser driver which element to act on. It can be a CSS selector, an XPath expression, an element id, or a higher-level query such as “the button whose accessible name is Sign in”. Choosing locators well is the single biggest factor in whether a UI suite survives a redesign.
Example
The same button located three ways:
// Playwright: user-facing, preferred
page.getByRole('button', { name: 'Sign in' });
// Playwright: dedicated test attribute
page.getByTestId('login-submit');
// Playwright: CSS, tied to markup structure
page.locator('form.login > button.btn-primary');
// Selenium 4
driver.findElement(By.id("login-submit"));
driver.findElement(By.cssSelector("[data-testid='login-submit']"));
What makes a good locator
- It describes what the user sees. Role, label and visible text change only when the user-facing behaviour changes, which is exactly when the test should be updated anyway.
- It is unique. Playwright locators are strict: an action on a locator that matches two elements throws instead of silently picking the first.
- It does not depend on layout. Long paths like
div > div:nth-child(3) > spanbreak when a wrapper is added. - It is stable across builds. Generated class names from CSS-in-JS tools and auto-incremented ids change between deployments.
A common priority order is: role and accessible name, then label or placeholder, then a data-testid agreed with developers, then CSS, then XPath as a last resort.
Lazy versus eager
A Playwright Locator is lazy. It stores the query and re-resolves it every time you act or assert, which is why it cannot go stale. Selenium’s findElement is eager: it returns a WebElement reference to the node that existed at that moment. If the DOM re-renders, that reference can become stale, so Selenium code usually stores By objects and finds the element when it is needed.