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:
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
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?