Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 35 ยท Finding Elements

CSS Selector Locators

Use CSS selectors as Selenium locators: ids, classes, attribute matches, combinators and structural pseudo-classes, and why CSS is the default choice.

If you only learn one locator strategy, learn CSS selectors. They can express everything the simple locators can (ids, classes, tags, attributes) and much more: elements inside other elements, the third item in a list, a link whose address ends with .pdf. They are also fast, readable to anyone who writes stylesheets, and understood by every browser.

In Selenium you use them with By.CSS_SELECTOR. The selector syntax is exactly the one you use in a stylesheet or with document.querySelector, which is why the runnable stand-ins in this lesson are real: the browser's own selector engine is the engine behind CSS locators, and you can test selectors with querySelectorAll before putting them in a test. The Selenium calls themselves are read-only.

Python
from selenium.webdriver.common.by import By

driver.find_element(By.CSS_SELECTOR, "#email")
driver.find_elements(By.CSS_SELECTOR, "ul.menu > li")

Why CSS is the usual default

Why start with CSS

Expressive Attributes, structure and combinations in one string.
Fast and standard Browsers implement it natively.
Readable Short selectors a teammate understands.

Reach for XPath only when CSS cannot say it.

1 / 2

CSS has two limits that matter for testing: it cannot match an element by its visible text (the :contains() you may remember is jQuery, not CSS), and it cannot walk up to a parent in a locator. XPath handles both. Everything else is usually shorter in CSS.

The basic building blocks

Selector Meaning Example
tag Elements of this type button
#id Element with this id #email
.class Elements with this class .error
tag.class Combined, no space button.primary
.a.b Both classes on one element .btn.primary
* Any element form *

Unlike By.CLASS_NAME, CSS handles several classes on one element, which is a big reason to prefer it.

Attribute selectors

Attributes are where CSS locators shine, because modern pages often have attributes meant for exactly this, such as data-testid.

Selector Meaning
[type] Has the attribute
[type="email"] Attribute equals the value exactly
[href^="https"] Value starts with
[href$=".pdf"] Value ends with
[class*="error"] Value contains the text
[data-testid="save"] A test hook, usually the most stable choice
input[name="q"][type="search"] Several attributes together

Quote attribute values with double quotes. When you write them inside a Python string that already uses double quotes, use single quotes outside, or escape with a backslash.

Combinators: relationships between elements

Combinator Meaning Example
space Any descendant form input
> Direct child only ul.menu > li
+ The element immediately after label + input
~ Any later sibling h2 ~ p

The difference between the space and > is important. nav a matches every link anywhere inside the nav, even in nested lists; nav > a matches only links that are direct children.

Structural pseudo-classes

Selector Meaning
:first-child, :last-child First or last child of its parent
:nth-child(3) The third child of its parent
:nth-child(odd) Every odd child
:nth-of-type(2) The second element of its tag type among siblings
:not(.disabled) Elements that do not match
:checked, :disabled, :enabled Form state
:has(.badge) Elements that contain a matching descendant (supported in current browsers)

:nth-child counts position among all siblings, not just those that match the rest of the selector. That surprises almost everyone once, and the stand-in below makes it visible.

A stand-in: trying selectors on a live snippet

The code builds a page and runs selectors with querySelectorAll, which is the same engine Selenium's CSS locator ends up using. Run it, then edit the selector list to experiment.

JS Selectors on a sample page

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare #main-nav a (four links, including the nested one) with ul.menu > li > a (three, only the top level). Count how many matches each selector gives before you rely on it in a test.

The nth-child trap

:nth-child(n) looks at the element's position among all its siblings. In the list below, the paragraph is the second child, so p:nth-child(2) matches it, but p:nth-child(1) matches nothing because the first child is a heading. :nth-of-type counts only elements of the same tag.

JS nth-child versus nth-of-type

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When you want "the second paragraph", use :nth-of-type(2). When you want "the second item in this list of identical items", both work, but positions are brittle: if someone adds an item above, your test clicks the wrong one. Prefer attributes over positions.

Using selectors well

  • Keep them short. [data-testid="save"] beats div.container > div:nth-child(3) > button.
  • Stay close to meaning. Choose attributes that describe purpose (name, aria-label, data-testid), not layout.
  • Test in the browser first. In the DevTools Elements panel you can run document.querySelectorAll("your selector") in the console, or search with Ctrl+F, and see how many matches there are. Every Selenium locator you write should match what you expect.
  • Count matches. If a selector should find one element but finds three, find_element will silently return the first and your test may click the wrong button.
Python
# a locator inside a page object (see the Page Object lesson)
SAVE_BUTTON = (By.CSS_SELECTOR, "[data-testid='save']")
driver.find_element(*SAVE_BUTTON).click()

How to rank locators by stability is the topic of Choosing Stable Locators.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which selector matches links whose href ends in .pdf?

    $= means the attribute value ends with the text. ^= means starts with and *= means contains.
  2. 2. What is the difference between 'nav a' and 'nav > a'?

    A space is the descendant combinator and > is the child combinator. Nested links match the first but not the second.
  3. 3. Why can't a CSS locator match an element by its visible text?

    CSS selects by structure and attributes. The :contains() pseudo-class comes from jQuery and is not valid CSS, so text matching needs XPath.
  4. 4. In '#box p:nth-child(1)' where the first child of #box is an h2, what matches?

    nth-child counts position among all siblings. The first child is the h2, which is not a paragraph, so the selector matches nothing.

Summary

  • By.CSS_SELECTOR is the best default locator: expressive, fast and standard.
  • Ids, classes, tags and attribute matches (=, ^=, $=, *=) cover most needs; combinators describe relationships.
  • :nth-child counts among all siblings; :nth-of-type counts among the same tag.
  • CSS cannot match visible text or move to a parent; XPath can.
  • Check how many elements a selector matches before trusting it.
  • The DOM calls in the stand-ins use the browser's real selector engine; the Selenium calls are read-only.

Next, handle what CSS cannot in XPath Locators.