Skip to content

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.

SelectorFinds
#login-buttonThe element with the ID login-button.
input[name=email]The input field whose name is email.
button[type=submit]A submit button.
.dashboardAn element with the class dashboard.
h1The main heading of the page.
button.loginA button with the class login.

Find a selector with your browser's Inspect tool#

  1. Open the page in your web browser.
  2. Right-click the element, such as the sign-in button, and choose Inspect. The developer tools open, with the element's code highlighted.
  3. Look for an id, name, type or class on that element.
  4. Write a selector from it. For example, <input name="email"> becomes input[name=email], and <div id="menu"> becomes #menu.
  5. 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 shows null, try again.
  6. Paste the selector into the step's selector field.

Choose selectors that last#

  • Prefer IDs and name values, such as #email or input[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_text reads 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.

Last updated