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 by.className or by.id.
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?
We actually don’t run any tests in Internet Explorer any more since these weren’t finding any browser specific bugs (we do exploratory testing in Internet Explorer instead).
Yes, I know that Selenium 3 has been out for a while, but I’ve finally got around at looking at updating our end-to-end tests to use it. Newer versions of Firefox require Geckodriver which require Selenium 3.3+ so it’s a forced upgrade of sorts.