Xpath Vs CSS Selector: Key Differences
By Mohit Joshi, Community Contributor - September 17, 2024
A locator is a code snippet that identifies any web element on a web page. It helps testers interact with web components and observe the state of specific elements on the web page. Locators are the fundamental building block of testing, without which you can’t test specific elements.
Moreover, choosing the best locator that caters to your requirements is equally important as it affects the flakiness and reliability of the test outputs.
This guide discusses two widely used locators, Xpath and CSS selectors, and helps you understand their differences.
What is XPath?
XPath (XML Path Language) is a query language that is used to navigate and select elements and attributes in XML and HTML documents. It’s commonly used for web automation, allowing testers to locate and interact with elements on a page accurately.
XPath is highly versatile and supports complex queries, making it a popular choice in testing frameworks like Selenium, Cypress, Playwright, etc. Its ability to traverse through various levels of the document structure makes it an essential tool for handling dynamic and complex web elements.
XPath Expression
XPath expressions consist of fundamental units of XML called nodes. Nodes are fundamental components of the document that help structure the webpage, such as elements, attributes, text, comments, etc.
The basic syntax for writing an XPath is as follows:
Xpath =//tagname[@Attribute='value']
1. Absolute XPath
It is a direct method of locating elements on the web. It defines the element from the root element of the document and continues until the target node. This approach to writing Xpath is not very flexible and couldn’t be used for dynamic elements. It starts with a ‘single-slash’.
For example, consider the HTML below:
<html> <head></head> <body> <form id="loginForm"> <input name="name" type="text" placeholder="First Name" /> <input name="name" type="text" placeholder="Last Name" /> <input name="email" type="text" placeholder="Email" /> <input name="password" type="password" placeholder="Enter Password" /> <input name="loginButton" type="submit" value="Sign Me Up" /> </form> </body> </html>
The Absolute XPath syntax to select the email field is:
html/body/form/input[3]
2. Code Walkthrough
It starts at the document’s root by selecting the ‘HTML’ tag. Then, a single slash ‘/’ separates it from another tag, indicating that it is moving down one level to its child elements until it reaches the first ‘form’ tag. It then goes one level below and locates the third ‘input’ element of the same ‘form’ parent tag.
The form/input script selects all the input elements; therefore, square brackets ‘[ ]’ are used to create a filter and select only a specific element inside the input tag.
3. Relative or Dynamic XPath
A relative XPath does not require long XPaths; instead, it can be written from anywhere in the middle of the document. It starts with a ‘double-slash’ indicating a break in the absolute path. It selects nodes regardless of their position in the hierarchy.
For example, to select the same ‘email’ field of the above example using Relative XPath:
//form/input[3]
Read More: How to use XPath in Selenium?
XPath Axes Methods
In an XML document, certain methods are used to search and locate multiple nodes from the current node context. These methods are known as XPath Axes Methods. There are several XPath methods available.
The following example of an XML document will help you understand some of the most common Axes methods.
<?xml version="1.0" encoding="UTF-8"?> <carshowroom> <car> <model>Ferrari</model> <price>3 million </price> </car> <car> <model>Audi</model> <price>8 million</price> </car> </carshowroom>
1. Child
It selects all the children elements of the current node.
Syntax:
child::node
Example:
/carshowroom/child::car
This expression selects both <car> elements (<car> with Ferrari and <car> with Audi).
2. Parent
It selects the parent node of the current node.
Syntax:
parent::node
Example:
//model[text()='Ferrari']/parent::car
This expression selects the <car> element that contains the <model> element with the text “Ferrari“.
3. Ancestor
It selects all the ancestors (parents, grandparents, etc.) of the current node.
Syntax:
ancestor::node
Example:
//price[text()='3 million']/ancestor::carshowroom
This expression selects the <carshowroom> element, which is the ancestor of the <price> element with the text “3 million“.
4. Preceding
Syntax:
preceding::node
Example:
//price[text()='8 million']/preceding::model
This expression selects the <price> element (<price>3 million</price>) that follows the <model> element with “Ferrari” in the document. In this specific example, it refers to the price associated with the Audi model since “following” would include all nodes appearing after the <model> node, including other sibling <price> nodes.
Read More: XPath in Appium – Tutorial
Advantages of XPath Selectors
XPath offers several key advantages that make it a powerful and flexible tool for navigating and selecting elements in complex web structures.
- XPath expressions are bidirectional, which means they can locate HTML or XML elements by traversing from parent to child and vice versa.
- It can locate elements at any position on the document and does not have to start navigating from the beginning of the document.
- It can use numerous operators to search for elements based on complex queries. For instance, in the above example, using //car[price > 5 million] will filter out all the <car> elements that have a price value of more than 5 million.
- It supports various ways to locate an HTML element on the document. In addition to attribute value and content, it can also search elements by establishing a parent-child relationship among the elements of the DOM.
Disadvantages of XPath Selectors
Despite its versatility, XPath has a few limitations that can impact performance and usability in certain web automation scenarios.
- XPath expressions can become very complex at times, especially when dealing with highly nested elements.
- Using relative XPath solves a lot of trouble in locating dynamic elements. However, there is still a chance that XPath will fail while locating them.
Read More: Quick XPath Locators Cheat Sheet
How do you check the XPath Expression in a browser?
First, find the element’s XPath and relative XPath, then check it on the browser.
In this example, find the Xpath of the Search box on Google.com.
To check the XPath of any element on a webpage, right-click on the webpage and navigate to the inspect element section.
In the Elements section, right-click on the code of the Search box and navigate to copy. Here, you will find two options: ‘Copy XPath’ or ‘Copy full XPath’. The latter gives the absolute XPath. However, the former gives the relative XPath.
Once you have found the XPath, check the XPath expression in the browser. To do so, in the same place, i.e., the Elements section, press Ctrl + F. Here, paste the XPath to validate the element.
Here’s the full XPath:
/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/textarea Here’s the relative XPath: //*[@id="APjFqb"]
What is a CSS Selector?
A CSS selector is a pattern used to select and style HTML elements based on their attributes, classes, IDs, and hierarchy in the document. In web automation and testing, CSS selectors are widely used to locate elements on a webpage precisely.
CSS selectors are typically faster and more straightforward than XPath for selecting elements, especially in static or predictable DOM structures. They are supported by popular automation tools like Selenium, Cypress, and Playwright. CSS selectors allow for efficient and readable test scripts, making them a go-to choice for many testers.
Read More: How to create browser-specific CSS code
The basic syntax of the CSS selector is as follows:
selector[attribute="value"]
Types of CSS Selectors
CSS selectors can be classified into several categories based on their manner of targeting HTML elements. In the context of Selenium, CSS selectors can be of 4 types. You can understand them using the BStack Demo website as an example of how to locate HTML elements from each CSS selector.
1. ID attribute selector
It is used to locate an HTML element using a specific ‘id’ attribute. Since IDs are unique and reserved for a specific element only, it efficiently locates a specific element. An “id” in CSS is denoted by a “#” sign.
The basic syntax for the ID attribute selector is as follows:
driver.findElement(By.cssSelector("<tagname>#<id value>"));
For example, to select the ‘orders’ tab in the website using ‘id’, the following syntax can be used:
driver.findElement(By.cssSelector("a#orders"));
Or
driver.findElement(By.cssSelector("#orders"));
Or
driver.findElement(By.cssSelector("a[id=orders]"));
Read More: Top responsive CSS frameworks
2. Class attribute selector
Here, an element is located using its ‘class’. A ‘class’ in CSS can be shared by several elements therefore, its primary purpose is to select all the elements at once that share a similar class. A “class” in CSS is denoted by a “.” sign.
The basic syntax for the class attribute selector is as follows:
driver.findElement(By.cssSelector("<tagname>.<class value>"));
For example, use the common class they share to select all the navbar elements at once.
driver.findElement(By.cssSelector("a.Navbar_link__3Blki"));
Or
driver.findElement(By.cssSelector(".Navbar_link__3Blki"));
Or
driver.findElement(By.cssSelector("a[class='Navbar_link__3Blki']"));
3. Other attributes
You can also use attributes other than class, to target HTML elements. However, IDs and classes are widely used in a web application script. The following syntax can be utilized to do so:
driver.findElement(By.cssSelector("<tagname><[attribute=Value of attribute]>"));
For example, to select the ‘iPhone 12’ product you use the ‘alt’ attribute inside the ‘img’ tag.
driver.findElement(By.cssSelector("img[alt=iPhone 12]"));
Read More: Understanding Sibling Selectors in CSS
4. Attributes combinator
From the above example, it is understood how to use a single attribute to locate an HTML element. However, in certain scenarios, a single attribute isn’t very useful, and you will be required to combine multiple attributes.
- Combining ID and Attribute
In certain situations, you need to combine the ID attribute with other attributes to locate an element uniquely.
The syntax followed here is:
driver.findElement(By.cssSelector("<tagname>#<id>[attribute='<attribute value>']"));
Here, the ‘Offers’ tab can be located by combining the ‘ID’ attribute with the ‘strong’ attribute of the element. The resulting expression will be:
driver.findElement(By.cssSelector("a#offers[strong='Offers']"));
- Combining Class and Attribute
There can be several web elements inside a class; therefore, to target a specific element of a class, combine the class with any other attribute to uniquely locate that element.
The basic syntax is as follows:
driver.findElement(By.cssSelector("<tagname>.<class>[attribute='<attribute value>']"));
Here, the iPhone 12 product can also be located by combining the class attribute with the data-sku attribute of the element. The resulting expression will be:
driver.findElement(By.cssSelector("div.shelf[data-sku='iPhone12-device-info.png']"));
Read More: CSS Selectors Cheat Sheet (Basic & Advanced)
Advantages of CSS Selectors
- CSS selectors are easy to understand and straightforward to use.
- CSS selectors target elements based on attributes, classes, and states. Therefore, they are not vulnerable to the dynamic nature of elements.
Disadvantages of CSS Selectors
Unlike XPath selectors, CSS selectors can’t traverse bidirectionally; that is, they can only traverse from parent to child element while locating an element and not vice versa.
Read More: CSS Selectors in Selenium
Differences between XPath vs CSS Selector
Here’s a detailed comparison of XPath and CSS selectors, highlighting their key differences to help you choose the best option for your web automation needs.
Aspect | XPath Selector | CSS Selector |
---|---|---|
Direction | It is bidirectional, which implies that you can traverse from parent element to child and vice versa. | It is unidirectional, implying that you can traverse only from parent to child elements. |
Performance Speed | Slower than CSS selector | Faster |
Ease of Understanding | Complex expressions | Simpler syntax, easy to understand |
Availability of Axes | XPath generally has axes to locate elements. | CSS Selector uses attribute-based locators to identify elements. |
Precision | Precise locator | Locating elements using the surrounding context |
Scope of Selection | It can select elements, attributes, and text nodes. | Can’t directly select text node |
XPath vs CSS selector: What to Choose?
Choosing between the two selectors largely depends upon the project requirements and the context in which they are being used, such as web development, automation testing, etc. Both selectors have pros and cons, as discussed in the blog.
However, you may also consider a few situations to help you decide which selector to choose.
- If you want to write complex queries, XPath is a better option than CSS selector; however, you may utilise the latter for simple ones.
- If you want to locate elements by directly matching them with the text or partial matching, then XPath should be used, as it is not feasible to perform this with CSS selectors.
- CSS selectors should be preferred to locate dynamic elements.
Most common scenarios create confusion between the two, which to use when should be solved by these points. However, one should always thoroughly consider one’s project requirements to use selectors efficiently.
Conclusion
Selectors are used in programming to target HTML elements based on their type, attributes, values, position in the DOM, etc. It is crucial to focus on picking the best selectors for your tests, as failing to do so results in flakiness in the test output and inconsistent results.
Xpath and CSS are two such selectors that are widely used among testers because they can locate elements in the DOM. Although these are two different ways of locating elements, both can be extremely useful for specific purposes.
CSS selectors are often preferred for their efficiency, particularly with dynamically changing elements. However, XPath is also useful in certain cases, including creating complex queries and bidirectional traversing from child to parent elements and vice versa — tasks that CSS selectors may not perform well.
Regardless of your choice of Selectors — XPath or CSS, BrowserStack Automate enables you to execute automated tests across a wide range of real browsers and devices. With its scalable infrastructure and parallel testing capabilities, BrowserStack Automate ensures fast, reliable testing without the need to maintain your own test environments.