What is the difference between a CSS and XPath selector? And which is better with respect to performance for cross-browser testing?

CSS selectors perform far better than XPath selectors, and it is well documented in Selenium community. Here are some reasons:

  • XPath engines are different in each browser, hence making them inconsistent
  • Internet Explorer does not have a native XPath engine, and therefore Selenium injects its own XPath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
  • XPath expressions tend to become complex and hence make them hard to read in my opinion

However, there are some situations where you need to use an XPath selector, for example, searching for a parent element or searching element by its text (I wouldn’t recommend the latter).

You can read blog from Simon here. He also recommends CSS over XPath.

If you are testing content, then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles, etc. Here is my blog post that explains it in detail.

Thanks to parishodak, here is the link which provides the numbers proving that CSS performance is better.

Leave a Comment