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.
Answer from nilesh on Stack Overflowselenium - What is the difference between a CSS and XPath selector? And which is better with respect to performance for cross-browser testing? - Stack Overflow
html - How can I find an element by CSS class with XPath? - Stack Overflow
Need help and explanation on CSS selector/Xpath for finding urls of products in this site
Different ways to get xpath elements and CSS selectors
It's contentious.
personally, I do everything with xpath. For a few reasons. Firstly, I've never found an element I couldn't get with xpath. Secondly, xpath allows me to navigate a DOM's hierarchy at will. And lastly, since xpath satisfies the first two, I don't feel the need to remember any extra syntax.
I have heard it said it's slower. If so, it's measured in milliseconds and the several hundred thread.sleeps left over in the framework from the devs before me are of much greater concern than me using xpath.
More on reddit.comWhy do CSS Selectors have higher priority over XPath expressions?
Which XPath can be replaced by CSS Selector?
Why Is XPath Preferred Over CSS Selector?
Videos
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.
I’m going to hold the unpopular on SO Selenium tag opinion that an XPath selector is preferable to a CSS selector in the long run.
This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.
Performance difference
Let's first tackle "the elephant in the room" – that XPath is slower than CSS.
With the current CPU power (read: anything x86 produced since 2013), even on BrowserStack, Sauce Labs, and AWS VMs, and the development of the browsers (read: all the popular ones in the last five years) that is hardly the case.
The browser's engines have developed, the support of XPath is uniform, and Internet Explorer is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against Internet Explorer 8?
If there is a difference, it is in a fraction of a millisecond.
Yet, most higher-level frameworks add at least 1 ms of overhead over the raw selenium call anyway (wrappers, handlers, state storing, etc.); my personal weapon of choice – Robot Framework – adds at least 2 ms, which I am more than happy to sacrifice for what it provides. A network round trip from an AWS US-East-1 to BrowserStack's hub is usually 11 milliseconds.
So with remote browsers, if there is a difference between XPath and CSS, it is overshadowed by everything else, in orders of magnitude.
The measurements
There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.
The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the HTML content as writing this post:

Here's the test code (Python):
from selenium import webdriver
import timeit
if __name__ == '__main__':
xpath_locator = '//div[@class="button-section col-xs-12 row"]'
css_locator = 'div.button-section.col-xs-12.row'
repetitions = 1000
driver = webdriver.Chrome()
driver.get('https://www.browserstack.com/')
css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)",
number=repetitions, globals=globals())
xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)',
number=repetitions, globals=globals())
driver.quit()
print("CSS total time {} repeats: {:.2f} s, per find: {:.2f} ms".
format(repetitions, css_time, (css_time/repetitions)*1000))
print("XPATH total time for {} repeats: {:.2f} s, per find: {:.2f} ms".
format(repetitions, xpath_time, (xpath_time/repetitions)*1000))
For those not familiar with Python – it opens the page, and finds the element – first with the CSS locator, then with the XPath locator; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.
The locators are:
- for XPath – "a div element having this exact class value, somewhere in the DOM";
- the CSS is similar – "a div element with this class, somewhere in the DOM".
It is deliberately chosen not to be over-tuned; also, the class selector is cited for the CSS as "the second fastest after an id".
The environment – Chrome v66.0.3359.139, ChromeDriver v2.38, CPU: ULV Core M-5Y10 usually running at 1.5 GHz (yes, a "word-processing" one, not even a regular Core i7 beast).
Here's the output:
CSS total time 1000 repeats: 8.84 s, per find: 8.84 ms XPath total time for 1000 repeats: 8.52 s, per find: 8.52 ms
Obviously, the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the XPath selector is faster" – sometimes it is, but sometimes it's CSS.
Let's try with another set of locators. It is a tiny-bit more complicated—an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):
xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'
The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:
CSS total time 1000 repeats: 8.60 s, per find: 8.60 ms XPath total time for 1000 repeats: 8.75 s, per find: 8.75 ms
A difference of 0.15 ms.
As an exercise—the same test as done in the linked blog in the comments/other answer—the test page is public, and so is the testing code.
They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?
The same code as above, with these changes in:
The URL is now
http://the-internet.herokuapp.com/tables; there are two tests.The locators for the first one - "Finding Elements By ID and Class" - are:
css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"
And here is the outcome:
CSS total time 1000 repeats: 8.24 s, per find: 8.24 ms XPath total time for 1000 repeats: 8.45 s, per find: 8.45 ms
A difference of 0.2 milliseconds.
The "Finding Elements By Traversing":
css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"
The result:
CSS total time 1000 repeats: 9.29 s, per find: 9.29 ms XPath total time for 1000 repeats: 8.79 s, per find: 8.79 ms
This time it is 0.5 ms (in reverse, XPath turned out "faster" here).
So five years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.
The Best/Fastest/Hip Strategy?
So, out of XPath and CSS, which of the two to choose for performance? The answer is simple – choose locating by id.
Long story short, if the id of an element is unique (as it's supposed to be according to the specifications), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.
Fun fact - the webdriver protocol actually does not support locator strategy "by id". When one uses By.ID in selenium, what it actually does is to transform it to a css selector in the form "any element having an id attribute with the requested value".
Still, the browsers optimize the css engines heavily, and it ends up in the advantage section of the DOM representation.
Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"
The XPath advantage
With the performance out of the picture, why do I think XPath is better? Simple – versatility, and power.
XPath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than CSS.
For example, navigation in every direction in the tree—find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions—cond1 and not(cond2 or not(cond3 and cond4)); embedded selectors —"find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text)—however frowned upon this practice is. It does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).
The stepping in CSS is definitely easier—one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities XPath has quickly overcomes CSS.
And purely subjective – a complex CSS expression is much harder to read than a complex XPath expression.
Outro ;)
Finally, again very subjective - which one should we chose?
IMO, there isn’t any right or wrong choice—they are different solutions to the same problem, and whatever is more suitable for the job should be picked.
Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.
This selector should work but will be more efficient if you replace it with your suited markup:
//*[contains(@class, 'Test')]
Or, since we know the sought element is a div:
//div[contains(@class, 'Test')]
But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:
//div[contains(concat(' ', @class, ' '), ' Test ')]
If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):
//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]
Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.
Most easy way..
//div[@class="Test"]
Assuming you want to find <div class="Test"> as described.