Selenium CSS Selectors
A CSS selector points to an element using the same syntax web designers use to style pages. Selenium borrows this syntax to locate elements quickly. CSS selectors usually run faster than XPath in most browsers.
Diagram: CSS Selector Pattern
tag#id.class[attribute='value'] | | | | | | | attribute match | | class match | id match tag match
Basic Selector Types
Tag Selector
driver.findElement(By.cssSelector("input"));Matches the first input tag found on the page.
ID Selector
driver.findElement(By.cssSelector("#email"));The hash symbol targets an element by its id attribute.
Class Selector
driver.findElement(By.cssSelector(".btn-primary"));The dot symbol targets an element by its class attribute.
Combining Tag With ID Or Class
driver.findElement(By.cssSelector("input#email"));This matches an input tag that also has the id email, reducing the chance of matching the wrong tag type.
Attribute Selectors
driver.findElement(By.cssSelector("input[name='username']"));This matches an input tag where the name attribute equals username exactly.
Partial Attribute Match
input[id*='user']
The asterisk matches any id attribute containing the text user anywhere inside it.
input[id^='user']
The caret matches any id attribute starting with the text user.
input[id$='name']
The dollar sign matches any id attribute ending with the text name.
Child And Descendant Selectors
Direct Child
div.form > input
The greater-than symbol matches an input tag that sits directly inside a div with class form.
Any Descendant
div.form input
A space between selectors matches an input tag anywhere inside the form div, at any depth.
nth-child Selector
ul li:nth-child(3)
This matches the third list item inside a ul tag, useful for picking one row from a repeated list without a unique attribute.
XPath Versus CSS Selector
| Feature | XPath | CSS Selector |
|---|---|---|
| Can select parent from child | Yes | No |
| Can match by visible text | Yes | No |
| Speed in most browsers | Slower | Faster |
| Readability | Longer syntax | Shorter syntax |
Practical Example
A checkout page shows multiple Add to Cart buttons, one per product row. Each button shares a class but sits inside a unique product container.
div.product-card[data-id='102'] button.add-to-cart
This selector finds the Add to Cart button only within the product card whose data-id equals 102, avoiding clicks on the wrong product.
