Difference between Xpath And CSS

Posted By : Anuj Gupta | 28-Aug-2019

 

While developing any Web application, elements are assigned attributes so that at time of testing, it becomes easy to locate that element. In automation testing using selenium, there are different types of locators which can be used to locate elements but most preferred locators are XPath and CSS locators because with the help of these locators we can access the web elements which cannot be accessed using id or class. Many people get confused between these two selectors. So first we will understand their meaning.

 

CSS stands for Cascading style sheet. It is used for styling the different web page elements like setting the font size, width, height etc. In selenium, we can use CSS locators to select a particular element on a webpage and perform the desired operation on that element.

CSS selectors can be used to locate the element by using the following formats:

  1. Tag and ID 
  2. Tag and class
  3. Tag and attribute
  4. Tag,class and attribute
  5. Inner text

 

So, using the above formats CSS selector can be used to locate elements.

XPath is a query language that is also used to access web elements in XML. document. It generally defines the pattern in order to select a particular element on the webpage. Both are used for the same purpose that is to find the web elements on the page but the main difference is CSS locators are used to find web element by traversing down the DOM(from parent to child) but using XPath traversing in DOM tree is possible in both ways (from parent to child as well as from child to parent).

 

Also while doing cross-browser testing, it is advisable to use CSS selectors as XPath is not that compatible with IE browser or it can be slow if used in IE. Also on selenium official site following message displays regarding this:

 

"Notwithstanding, WebDriver utilizes a browser's local XPath abilities at every possible opportunity. On those browsers that don't have local XPath support, we have given our very own execution. This can prompt some unforeseen conduct except if you know about the distinctions in the different XPath engines."

 

In addition to this, CSS is shorter, cleaner and easier to read. For example, a button having id “opener” will be written in CSS as “#opener” but in XPath, it would be written as “//*[@id="opener"]”.

 

My general locator technique is ID first, CSS selector for everything else. When nothing else works then use XPath.Whether you use XPath or CSS, it should be in well-written format. CSS or XPath, if written badly will lead to slowing up the execution of test scripts.

 

Thanks

 

Related Tags

About Author

Author Image
Anuj Gupta

Anuj is a passionate QA engineer and an optimistic person. He is fond of playing Chess and Basketball. He always comes up with the new ideas and is a good team player.

Request for Proposal

Name is required

Comment is required

Sending message..