Automated Acceptance Testing Automated Testing Selenium WebDriver

Why you should use CSS selectors for your WebDriver tests

I didn’t used to be a fan of CSS selectors for automated web tests, but I changed my mind.

The reason I didn’t use to be a fan of CSS selectors is that historically they weren’t really encouraged by Watir, since the Watir API was designed to find elements by type and attribute, so the Watir API would look something like:

browser.div(:class => 'highlighted')

where the same CSS selector would look like:


Since WebDriver doesn’t use the same element type/attribute API and just uses findElement with a By selector, CSS selectors make the most sense since they’re powerful and self-contained.

The the best thing about using CSS selectors, in my opinion, is the Chrome Dev Tools allows you to search the DOM using a CSS selector (and XPath selectors, but please don’t use XPath), using Command/Control & F:

chrome css selectors
Using CSS selectors to find elements in Chrome Dev Tools

So you can ‘test’ your CSS in a live browser window before deciding to use it in your WebDriver test.

The downside of using CSS selectors are they’re a bit less self explanatory than explicitly using by.className or

But CSS selectors are pretty powerful: especially pseudo selectors like nth-of-type and I’ve found the only thing you can’t really do in CSS is select by text value, which you probably shouldn’t be doing anyway as text values are more likely to change (since they’re copy often changed by your business) and can be localised in which case your tests won’t run across different cultures.

The most powerful usage of CSS selectors is where you add your own data attributes to elements in your application and use these to select elements: straightforward, efficient and less brittle than other approaches. For example:


How do you identify elements in your WebDriver automated tests?

Ask Me Anything Usability

AMA: automation hooks bad practice?

Miguel Juteau asks…

Some people contend that deploying markup code in production that contains automation hooks (e.g. Html5 data tags) is bad practice (for the same reason that we don’t deploy unit tests to production: it doesn’t serve the customer).
However it seems very desirable to build a solid contract for automation selectors that does not get affected by UI changes.

Any thoughts on that ?

My response…

Automated Testing Test Automation

The importance of testability, or how to avoid the nastiest xpath selector known to humankind

Our automated end-to-end tests for include searching for a domain and selecting a .com result from a screen that looks like this:

find a domain component.png

We want our tests to be consistent, so even though we search for a different address each time, we want to select the ‘.com’ address result each time by clicking ‘Select’ next to that result. But how do we click the correct ‘Select’ button when there’s so many of them?!?