Last week, our own Santiago Suarez Ordoñez gave a presentation to the San Francisco Selenium Meetup group that convinced us all to say no (for the most part) to XPath and yes to CSS Locators in our Selenium tests.
In his role as official Sauce Ninja and as a prolific poster in the Selenium forums, Santi has helped more users solve locator issues than possibly anyone else in the world. He’s previously written a number of blog posts on ways to improve locator performance. As Sauce CEO John Dunham puts it, “If there was a foursquare mayorship for locators, Santi would have it for a lifetime.”
Drawing from this experience, he gave us these four reasons for using CSS Locators:
1. They’re faster
2. They’re more readable
3. CSS is jQuery’s locating strategy
4. No one else uses XPATH anyways!
I can’t speak for everyone, but Santi sure sold me on point number one when he showed off the performance metric script he wrote a script that tested the speed of XPath vs the speed of CSS Locators. There wasn’t much of a difference in Firefox, Safari, or Chrome, but with IE, the results were undeniable. Take a look:
To underscore this even further, he also recorded a video in Sauce OnDemand that uses one heck of a cute kitten to illustrate just how slow XPath can be. The cat’s paw movements represent the test clicking through the different locators. The first batch of clicks uses CSS Locators and completes in under 30 seconds. The second batch, the XPath one, continues on for another eight minutes. Eight minutes!
During the rest of the presentation, Santi dives into writing both basic and more advanced CSS Locators. He also spends some time talking about when you shouldn’t use CSS Locators (yes, there are a few cases where it is not the right tool for the job). To see the talk in its entirety, check out the recording below. And if you’re thinking of switching over from XPath, but unsure of how to go about it, check out the nifty tool Santi wrote called cssify. It does the handy work of translating your XPaths to CSS automatically.