Playwright locator generator
The short answer: paste an element's HTML and get its Playwright locators, best first: getByRole with the element's accessible name, then label, placeholder, text, test id and CSS, in JavaScript or Python. A second tab turns an XPath into a CSS selector.
It runs in your browser; the HTML you paste is not sent anywhere. Each result also shows the matching Dejo step where there is one, since Dejo's steps use the same idea: button "Sign in" finds the element the way a person would.
Which Playwright locator to use
Playwright's documentation recommends "prioritizing user-facing attributes and explicit contracts", and says "CSS and XPath are not recommended as the DOM can often change leading to non resilient tests." Its built-in locators, in the order the generator tries them:
| Locator | Finds an element by |
|---|---|
getByRole | its role (button, link, textbox, heading...) and its accessible name |
getByLabel | the text of the label tied to a form control |
getByPlaceholder | an input's placeholder |
getByAltText | an image's text alternative |
getByTitle | its title attribute |
getByTestId | its data-testid attribute |
getByText | its text |
How the role and name are found
The role is the element's own role attribute, or the one HTML gives it: a link with href is a link, a button is a button, <input type="email"> is a textbox, <select> is a combobox, <h2> is a heading. The name comes from aria-labelledby, then aria-label, then a tied <label> for form controls, alt for images, or the element's own text for buttons, links and headings. That is the same order browsers use for these elements, which is what getByRole matches against.
When a locator stops working
A locator that worked yesterday can miss today when the site renames a button or wraps it in a new element. Dejo keeps up to nine ways to find each element and tries them in order, so one change rarely breaks a saved step. See what happens when a website changes.
Sources
- Playwright locators: playwright.dev/docs/locators
FAQ
What is the best Playwright locator?
Playwright recommends user-facing locators first: getByRole, then getByLabel, getByPlaceholder, getByText, getByAltText, getByTitle and getByTestId. Its docs say CSS and XPath are not recommended, because the DOM can often change and the test breaks with it.
How do I get the HTML of an element?
In Chrome DevTools, right click the element in the Elements panel, then Copy, then Copy element. Paste that here. To keep a label with its input, copy both, label first.
Can every XPath be turned into CSS?
No. CSS has no text(), no parent or sibling axes, and no or/and between conditions. The converter turns the common shapes (tags, attributes, contains, starts-with, positions) into CSS and says when an XPath has no CSS form, so you can use getByText or getByRole instead.