What is the best “By” selector for Selenium, CSS or XPath?

Short answer:

CSS

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
  2. You only want to support one selector type
  3. You need to do something only XPath supports
    Example -
    Only XPath support finding an element by moving back up the DOM

    DOM:

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

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

    XPath:
    .//*[@id='SubscribeFuLabel']/../..//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
  5. 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
  6. Beware browser tools that create CSS and/or XPath for you
    • Programmatically generated selectors are typically very fragile

Useful resources:

  1. http://www.w3schools.com/cssref/css_selectors.asp
  2. https://msdn.microsoft.com/en-us/library/hh781508(v=vs.85).aspx
  3. https://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx