Short answer:


Why CSS:

  1. It is easier to learn/understand
  2. It can do almost everything XPath can
  3. Typically faster than XPath
  4. It’s used a lot on the development side
  • JQuery uses CSS extensively
  • It's used to style web pages

Long answer:

It depends

The right type of selector depends on the context under which it is being used.  There are several different types of "By" selectors and they all have their strengths and weaknesses.

So when should you use XPath:

  1. The browser does not support CSS or the CSS selectors you need
  • Older browsers do not support all CSS features
  • Pages can be setup for legacy document or compatibility mode which can remove several of the modern CSS features
  • This is primarily seen in IE
  1. You only want to support one selector type

You need to do something only XPath supports
Example -
Only XPath support finding an element by moving back up the DOM


       <div class="Label">
         <label id="SubscribeFuLabel">Fu:</label>
         <a class="subscribe-button icon-feed" href="UNKNOWNURL">Subscribe</a>
         <div class="Label">
           <label id="SubscribeBarLabel">Bar:</label>
           <a class="subscribe-button icon-feed" href="UNKNOWNURL">Subscribe</a>


Real answer:

For the most part it doesn’t matter

There are many "By" selector types and they all have advantages and disadvantages. I have yet to be on a project where we just used one type of selector.  As long as you are creating good (work and are maintainable) selectors you really don’t need to stress out about what is the best selector.

Closing thoughts:

  1. The "best" selector for your team is largely a matter of what works and what is maintainable
  2. You are not tied to one "By" selector type
  3. Selenium supports several "By" selectors, not just CSS and XPath
  4. Avoid saving selectors as string, instead save them off as "By" objects
  • This make is easier to maintain your selectors
  1. Test your selectors before running your scripts
  • All modern web browsers come with developer tools that allow you to test selectors on any open web page
  1. Beware browser tools that create CSS and/or XPath for you
  • Programmatically generated selectors are typically very fragile

Useful resources: