7.5Finding the right element (selectors)
A selector tells obsrvly which element a step should use. Write it as a CSS selector. This is the same way web developers point to elements when they style a page.
| Selector | Finds |
|---|---|
#login-button | The element with the ID login-button. |
input[name=email] | The input field whose name is email. |
button[type=submit] | A submit button. |
.dashboard | An element with the class dashboard. |
h1 | The main heading of the page. |
button.login | A button with the class login. |
Find a selector with your browser's Inspect tool#
- Open the page in your web browser.
- Right-click the element, such as the sign-in button, and choose Inspect. The developer tools open, with the element's code highlighted.
- Look for an
id,name,typeorclasson that element. - Write a selector from it. For example,
<input name="email">becomesinput[name=email], and<div id="menu">becomes#menu. - Test it. Open the Console tab in the developer tools and enter
document.querySelector("input[name=email]"). If it shows your element, the selector works. If it showsnull, try again. - Paste the selector into the step's selector field.
Choose selectors that last#
- Prefer IDs and
namevalues, such as#emailorinput[name=email]. They rarely change. - Avoid long paths such as
div:nth-child(3) > div > span. They break when the page layout changes. - Ask your developers to add a fixed attribute for monitoring, such as
data-test="login". Then use[data-test="login"]. - If a selector matches several elements,
assert_textreads the first one. Make the selector match only the element you mean.
A wrong selector usually shows up as a step that times out. The step waits for an element that never appears.