CSS Selectors for Test Automation
On this page
CSS selectors are the workhorse of web test automation. Every browser has a fast native engine for them, Selenium sends By.ID, By.NAME and By.CLASS_NAME to the browser as CSS under the hood, and Playwright's page.locator('...') treats a plain string as CSS. This chapter covers the parts of CSS that matter for tests, and the parts that quietly make tests brittle.
The building blocks#
| Selector | Matches | Example |
|---|---|---|
tag |
elements of that type | button |
#id |
the element with that id | #username |
.class |
elements with that class (one of possibly several) | .email |
[attr] |
elements that have the attribute | [disabled] |
[attr='v'] |
attribute equals v
|
[name='my-text'] |
[attr^='v'] |
starts with | [name^='my-d'] |
[attr$='v'] |
ends with | [href$='.pdf'] |
[attr*='v'] |
contains | [href*='invoice'] |
A B |
B anywhere inside A
|
#table2 td.email |
A > B |
B that is a direct child of A
|
tr > td |
A + B / A ~ B
|
B right after / anywhere after sibling A
|
label + input |
:checked, :disabled, :not(...)
|
state and negation | input:not([disabled]) |
:nth-child(n) |
the n-th child of its parent | tr:nth-child(2) |
:has(...) |
elements that contain a match | label:has(input:disabled) |
Combine them without spaces to describe one element (input.form-control[name='my-text']), and with a space or > to describe a path.
Attribute selectors do most of the work#
The Selenium project's web form, https://www.selenium.dev/selenium/web/web-form.html, is a typical Bootstrap form: every input has the class form-control and a meaningful name. The class says how it looks; the name says what it is. Select on the name (tests/test_css.py):
from selenium.webdriver.common.by import By
FORM = "https://www.selenium.dev/selenium/web/web-form.html"
TABLES = "https://the-internet.herokuapp.com/tables"
def css(driver, selector):
return driver.find_elements(By.CSS_SELECTOR, selector)
def test_attribute_selectors(driver):
driver.get(FORM)
assert len(css(driver, "input[name='my-text']")) == 1
assert len(css(driver, "[name^='my-d']")) == 3 # my-disabled, my-datalist, my-date
assert len(css(driver, "input[type='checkbox']:checked")) == 1
assert len(css(driver, "input.form-control:not([disabled]):not([readonly])")) == 6
Things to notice:
-
Quote attribute values.
[name='my-text']works for any value; the unquoted form breaks as soon as a value contains a space, a dot or starts with a digit. -
Prefix and contains matches are blunt.
[name^='my-d']matched three fields here, which is fine for a count and dangerous for a click. Use them for families of elements whose names you control, such as[data-testid^='invoice-row-']. -
State pseudo-classes like
:checkedand:disabledread the live state of the element, not the original HTML attribute, so they reflect what the user has done.
Classes: use the ones that mean something#
By.CLASS_NAME and .class are fine when the class names a thing (.email, .invoice-total, .todo-list). They are brittle when the class names a look (.btn-primary, .mt-3, .col-md-4) or is generated by a CSS-in-JS tool (.css-1x2y3z, .sc-bdVaJa). Those change with every redesign or build.
The tables page shows the difference. Table 1 has no classes at all; table 2 marks every cell with what it holds:
<td class='last-name'>Smith</td>
<td class='first-name'>John</td>
<td class='email'>jsmith@gmail.com</td>
Semantic classes like these are nearly as good as test ids, and they are worth asking for.
Which selector for the "Place order" button is least likely to break when the design system is upgraded?
A design-system upgrade changes visual classes, generated class names and grid wrappers. The form's id and the button's submit type describe what the element does, and neither depends on how it is styled.
Combinators and position#
Descend from a stable ancestor instead of starting from the top of the page:
def test_combinators_and_position(driver):
driver.get(TABLES)
emails = css(driver, "#table2 tbody td.email")
assert [e.text for e in emails][:2] == ["jsmith@gmail.com", "fbach@yahoo.com"]
second = driver.find_element(By.CSS_SELECTOR, "#table2 tbody tr:nth-child(2) > td.email")
assert second.text == "fbach@yahoo.com"
#table2 tbody td.email reads well: the email cells in table 2's body. The second selector works too, but :nth-child(2) is a bet that Frank Bach will always be the second row. Sort the table and the bet is lost. Positions are acceptable when the order is the thing under test ("the newest message is first") and a smell everywhere else. Chapter 8 shows how to find a row by its content instead.
A detail that trips people up: :nth-child(2) means "the second child of its parent, if it also matches the rest of the selector", not "the second match". tr:nth-child(2) and td.email:nth-child(2) count different things. When you want "the second of these", count in code (emails[1]) or use Playwright's .nth(1).
:has() selects a parent#
For years CSS could only go down the tree, which was the main reason testers reached for XPath. The :has() pseudo-class, supported in current Chrome, Edge, Firefox and Safari, lets you select an element by what it contains:
def test_has_selects_a_parent(driver):
driver.get(FORM)
label = css(driver, "label:has(input:disabled)")
assert len(label) == 1
assert label[0].text.startswith("Disabled input")
"The label that contains a disabled input" was XPath-only territory before. tr:has(a[href='#edit']) and li:has(input:checked) work the same way. Check :has() against the oldest browser in your matrix before relying on it: older browser versions you may still test on do not support it.
You need the table row that contains a checked checkbox. Which selector does that in CSS alone?
:has() selects the element that contains a match. Option a selects the input, not the row (and only if it is a direct child of the row, which it never is inside a cell). There is no < combinator in CSS.
What CSS cannot do#
CSS cannot match an element by its text content. There is no button:contains('Save') in the standard; jQuery and some old tools added it, and it fails in Selenium with an invalid selector error. When the text is the best handle, use a role or label locator (chapter 5), Playwright's :has-text() extension, or XPath (next chapter).
Summary#
- Select on attributes that say what an element is (
name,type, semantic classes, test ids), not how it looks. - Start from a stable ancestor and keep the path short.
- Treat
:nth-child()as a statement that order matters; it usually does not. -
:has()covers most "parent of" cases that used to need XPath. - CSS cannot match on text.