Live demos are back. See Testim Mobile in action on Feb 21 | Save your spot

XPath vs CSS Selector: The Difference and How to Choose

The battle of XPath vs CSS Selector is one that people approach differently—mostly because of preferences rather than the various…

Testim
By Testim,
The battle of XPath vs CSS Selector is one that people approach differently—mostly because of preferences rather than the various implications of using either of the options. If you’ve ever had to pick between using XPath and CSS selectors, most likely the environment you were working in had more to do with your choice than the actual differences between the options. Instances where you’d weigh the options include when you want to scrape content from a live website or you’re conducting automated tests on the front end of your application.
This article will address the various differences between XPath and CSS. Along the way, we’ll talk about what each of the options brings to the table. By the end of this article, which option you should use is likely to become clear to you even if you aren’t considering its compatibility with your use case. You’ll also learn why one or the other can be a better option to use when testing your applications.
The cycle of making applications goes something like this; code, test, deploy, get feedback, patch, and do it all over again. At times there are different people at every stage, which makes things complicated. And skipping any phase can doom an the application’s usability. Testing is just as important as every other phase. It’s at the testing stage you could start looking at the XPath vs CSS selector.
Before we get deeper into the logic of the choice, let’s define each side and learn their respective pros and cons.

What Is XPath?

XPath stands for XML Path. It’s a query language that helps identify elements from an XML document. It uses expressions that navigate into an XML document in a way that can be traced from the start to the intended element—like forming a path from the start. We’ll discuss the syntax in greater depth shortly.

Advantages of Using XPath

  • XPath allows you to navigate up the DOM when looking for elements to test or scrape.
  • It’s compatible with old browsers (or it was at time of publishing—including older versions of Internet Explorer, which some corporations still use).
  • Creating in XPath is more flexible than in CSS Selector.
  • When you don’t know the name of an element, you can use contains to search for possible matches.

How to Create an XPath

XML path syntax uses tree diagram type flows to locate elements on an HTML page. Consider the form element in the search page markup below.

The full XPath to the search button inside the form would look like this:

/html/body/main-view//section/startpage-component//div/main/search-box-component//div/form/div/button

As seen in the full XPath, the document is broken down into the elements that essentially represent its skeleton. Going from top to bottom within the resulting document and listing every node, until you reach the desired element, is what becomes the XPath. Here’s a shorter way to write this.

//*[@id="scroll-container"]/main/search-box-component//div/form/div/button

And here’s a comprehensive table for the syntax of both XPath and CSS Selectors;

XPath vs CSS Selector Syntax Table from Slotix Git Repo
Now that you’ve got a sense of what XPath is and what it can do, let’s move on to CSS Selector.

What Is CSS Selector?

Most HTML pages are styled using cascading style sheet classes, also known as CSS. Identifying the various elements on a page based on styles requires you to select the class it falls into. Consider a CSS selector as that part of the style sheet that allows you to pick out the type of content to either test, edit, or copy. The CSS selectors identify the various elements in the DOM, and they affect or connect to these parts of the interface.
CSS selectors come in many types. This is mostly because unlike the tree or map build-up of the XPath option, selectors have actual names and categories. Here are some of the types.
  • Simple selectors: These search for elements based on their class or ID.
  • Attribute selectors: These pick up elements based on values assigned to them. I’ll provide some examples later on in this article.
  • Pseudo selectors: In situations where the states of elements are declared with CSS, such as check boxes or on-hover attributes, these come into use.

Advantages of Using CSS Selector

  • It’s faster than XPath.
  • It’s much easier to learn and implement.
  • You have a high chance of finding your elements.
  • It’s compatible with most browsers to date.

Expand Your Test Coverage

Fast and flexible authoring of AI-powered end-to-end tests — built for scale.
Start Testing Free

How to Create CSS Selectors

Let’s use the same image that we did earlier, with a search page’s markup displayed. You can do this on any web page by right-clicking and selecting Inspect Element. You should be able to create the CSS selector just as we did with the XPath.

In this case, the CSS selector would look like this.

div > form > div > button

Notice how much easier it is to read the CSS selector compared to the XPath. You can read this as, “The button is a child element of the div inside a form, which is itself inside the div type selector.”

To fully cover what’s possible with the CSS attribute selector, let’s consider a more specific markup example.

<ul>
    <li><a href="maps.google.com"> Google Maps Sub-domain </a></li>
    <li><a href="mail.icloud.com"> Link to iCloud Mail Services</a></li>
    <li><a href="mail.opera.com"> Opera Mail </a></li>
    <li><a href="mail.google.com"> Gmail Services </a></li>
</ul>

The selector applicable for finding specific elements in the above example would look like this.

a[href^="some value here"]

For instance, let’s say you want to pick out the <a> element that includes “mail” as a value. In that case, you’d use the * sign after the href key. This would give you:

a[href*="mail"]

This returns all the elements but the first one because it doesn’t have mail as the sub-domain.

What about instances where you’d like to select all elements ending in a certain value? Then you’d replace the * with a $. You can filter out entries that start with a certain value by using the ^ sign. There are plenty of such signs depending on the rules you’re using for selection.

Now you’ve had a mini tour of each option. So which one is right for you?

Which to Use: XPath or CSS Selector?

When you’re deploying software a product to a group of users, time is often of the essence. This statement alone should let you know what option is better for you to use. If your software testers decide to make their own test automation scripts, using the option that they already have experience with is the way to go. Besides, the execution time difference between XPath and CSS selectors is not such that you could do meaningful work while others wait. Such a negligible difference means that both options may be running neck-and-neck for you at this point.

As I mentioned at the start of this article, your environment kicks in more than any other variable. A limiting factor when dealing with selectors is the fact that they get more complex as the type of element evolves from simple through pseudo to combinators. Multiple selectors would also make it more complex to even use selectors in the first place.

“There has to be a better way of implementing test automation!” you might say. As with most repetitive processes, artificial intelligence is beginning to affect both options. Services like Testim have figured out quicker and more intuitive ways to run tests on elements on the DOM.

In the past, you had to generate paths or pinpoint selectors in the back-end by combing through all the markup. Now, services such as Testim take care of that for you. The company uses its artificial intelligence and algorithms to look at the entire DOM and identify elements by multiple attributes. Testim will look at class, parent/child, color, text, type, ID, or other attributes and find the item for you to run your tests. Using such a service stops your focus from being focused on XPath vs CSS Selector. Instead, you can focus more on the results.

Also, if you use Testim, working on the front end when creating automated tests also makes it easy to deploy products faster. You can use fewer code-critical skills to iterate on the testing and feedback phase of a product’s development life cycle.

What to read next

Understanding XPath