XPath vs CSS Selectors: Which One Should You Use and When?


Marijus Narbutas
In This Article
Key takeaways:
- XPath helps locate elements accurately based on the hierarchical HTML tree structure.
- CSS selectors locate elements based on CSS style attributes. Comparing XPath vs CSS selectors includes differences such as browser support, performance speed, filtering options, syntax, and others.
- While there aren’t clear answers in all use cases, CSS selectors are recommended in more scenarios.
Clicking buttons, ticking boxes, entering text, and performing various other operations are at the heart of browser automation. None of this can be performed without first locating the HTML elements in the website’s code. That’s the basic function of locators in testing, web scraping, or other automation tasks.
Web automation tools support a variety of locators, but the main debate comes down to XPath vs CSS selectors. One is more flexible and suitable for complex structures, while the other is faster and simpler to use. The choice gets more complicated when you consider the variety of use cases.
What Is XPath?
XPath (or XML Path Language) uses path expressions to find nodes or node-sets in an HTML or XML document. All elements of a website or web application can be accurately selected with XPath expressions, allowing much of the automation used in tools like Selenium, Playwright, Cypress, and others.
The query language uses path expressions to navigate the hierarchical tree structure from the start (root parent node) to the element the XPath selector locates. DOM (Document Object Model) trees are quite similar to the hierarchy found in traditional computer systems you might already be familiar with.
C:\Users\User\Pictures\Cats
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<div class="content">
<p>Sample text</p>
</div>
</body>
</html>
Basic XPath expressions—location paths—are similar in that they outline a sequence of steps to locate the element from the root of the XML or HTML document. Such expressions are called absolute XPaths.
/html/body/div/p
If any parent element in the hierarchy is modified or a new one is added, the whole structure changes, and the absolute XPath breaks. That's why absolute XPaths are less useful for web pages where dynamic elements frequently change. Many of the drawbacks of absolute XPaths are solved by relative or dynamic XPaths.
//p
Relative XPath expressions can start anywhere in the DOM tree. Its syntax uses the double forward slash (//) and is the preferred XPath expression with tools like Selenium. However, relative XPath expressions must use attributes, such as the class attribute, to provide context for identifying XML or HTML elements.
Attributes can make the XPath expression rather complicated and more difficult to write in larger HTML or XML documents. The upside is that small changes to the document won't affect the XPath selector. Here's how the class attribute is written: @class='content' before adding it into a relative XPath expression.
//div[@class='content']/p
The use of XPath expressions is generally the same throughout different use cases. Some practical differences might arise due to using different HTML elements or libraries, such as Python's lxml library for parsing.
What Are CSS Selectors?
CSS selectors are used to find elements in the HTML or XML document you want to style. That's the original function, but with tools like Selenium, you create CSS selectors to locate elements for automation purposes. The identification is based on various factors, such as name, hierarchy, ID, and class attributes.
CSS selectors are unidirectional, moving from parent elements to child elements but not vice versa. This makes them faster when running scripts and more straightforward to write than XPath expressions but less flexible for complicated DOM trees. This is reflected in the types and syntax of CSS selectors.
Simple CSS selectors find elements based on name, ID, or class attributes.
- Name (element) CSS selector for targeting all
<p>
elements.
p {
text-align: center;
color: red;
}
- ID CSS selector for targeting the element with the ID para1.
#para1 {
text-align: center;
color: red;
}
- Class CSS selector for targeting all elements with the class center.
.center {
text-align: center;
color: red;
}
Attribute CSS selectors find elements with a specified attribute. The example below targets all <a>
(anchor) elements that have a target attribute.
a[target] {
color: yellow;
}
Pseudo-class CSS selectors find elements in defined special states, such as highlighted or hovered-over buttons. The example below targets all elements that are in the hover state.
a:hover {
color: blue;
}
Pseudo-elements CSS selectors find a specific part of the element, such as the first letter, line, markers of lists, or dialog boxes. The example below targets the first line of text in every paragraph.
p::first-line {
font-weight: bold;
color: red;
}
Combinator CSS selectors find elements based on their relationship with other basic selectors. The example below targets all elements that are descendants of a specified element.
div p {
color: blue;
}
All the examples also assign color to the elements, as styling is the most common use case for CSS selectors. In web scraping or automation tasks, you'll need to define CSS selectors and then use a find_element command to perform an action or scrape the data from the XML or HTML elements.
element = driver.find_element(By.ID, "orders")
Note that some CSS selectors cannot be directly selected by the find_element method in Selenium or similar tools. Pseudo-classes, for example, might not be able to collect data from hovered elements straightforwardly, but automation tools provide a workaround that allows you to interact with the element before collecting the data.
XPath vs CSS Selectors: Key Differences
The differences in compatibility between XPath and CSS selectors are quite minimal. Even less popular automation and web scraping tools, such as Puppeteer or Playwright , support both XPath and CSS selectors. The challenges begin when you want to connect to different browser versions.
XPath selectors work with most modern and older browsers, while CSS selectors might not be supported by older browser versions. So, if you would like to run tests or web scrape on an older browser version, locating dynamic elements with CSS selectors might not be possible.
Older software does not support modern CSS standards, but this is also one of the reasons why CSS selectors work faster than XPath selectors. Another reason is that CSS selectors are unidirectional, which means they do not require traversing the entire DOM tree in the XML or HTML document.
XPath and CSS selectors also differ in their filtering options, with XPath often having more options than CSS selectors. Yet, CSS selectors are better for filtering dynamic elements, but both locators have various workarounds. The choice between XPath and CSS selectors might also depend on which one is easier for you to use.
While it's largely a matter of preference, some developers argue that creating CSS selectors is easier than working with various class attributes or other variables in XPath. The final decision on when to use XPath versus CSS selectors depends on your project and goals.
When to Use XPath vs When to Use CSS Selectors
Use Case | Details | XPath vs CSS Selectors Verdict |
---|---|---|
Large scraping projects | Requires robust and flexible selectors for complex web structures. | XPath offers more flexibility for handling nested elements and complex queries. |
Smaller Scraping Projects | Focuses on specific, well-defined elements with straightforward structures. | CSS selectors are generally faster and more readable for simple structures. |
Dynamic Website | Dynamic elements change frequently, requiring adaptable selectors. | XPath vs CSS selectors are a close comparison. XPath can handle complex dynamic content changes more effectively. However, Selenium can simulate interactions to help CSS selectors, and they are faster. |
Static Website | The structure remains constant, making it easier to target elements. | CSS selectors are more efficient for static content due to simplicity and speed. |
Old Browser | Needs compatibility with older browser versions that may not fully support modern CSS. | XPath is more reliable across older browsers, but modern browsers support both well. |
Modern Browser | Supports the latest web standards, allowing for more advanced selection techniques. | CSS selectors should be preferred for speed and readability in modern browsers. |
Frequent Automation Tasks | Requires reliable and maintainable selectors for repeated tasks. | CSS selectors are easier to maintain and read, but XPath can be more reliable for complex scenarios. For frequent use, the choice of XPath vs CSS selectors is up to the developer team. |
One-Time Automation Project | Focuses on quick setup and execution without long-term maintenance. | Both CSS selectors and XPath can work. XPath is more flexible for one-off complex queries, but CSS selectors are simpler for straightforward cases. |
Web Testing | Needs precise targeting of elements for interaction and validation. | CSS selectors are preferred due to being faster and more readable. However, XPath can be better in some complex test cases. |
Complex DOM Structures | Involves deeply nested or intricate HTML structures. | XPath is better suited for navigating complex hierarchies with precise queries. |
Simple DOM Structures | Involves straightforward HTML element structures with clear relationships. | CSS selectors are more efficient and easier to use for simple structures. |
Conclusion
It should be clear that the choice between XPath vs CSS selectors highly depends on your project, skills, and current infrastructure. In general, CSS selectors are recommended for testing and web scraping tasks due to their speed and straightforward expressions, while XPath expressions are often reserved for more complex queries.
FAQ
Which locator is faster in Selenium?
Locating HTML elements by their IDs is generally considered the fastest method. However, many modern web applications have dynamic IDs or lack IDs, which might create potential conflicts or complicate development. The next best option in terms of speed is using CSS selectors and then XPath expressions.
Why is XPath not recommended sometimes?
XPath expressions might be slower compared to other locators and can create difficulties with dynamic content that frequently changes. For this reason, other locators, such as CSS selectors, are easier to maintain and are more often recommended for larger projects.
How do CSS Selectors and XPath differ in execution?
XPath and CSS selectors differ in directionality, as the first is bidirectional, and the latter is unidirectional. This is one of the reasons why XPath is slower than CSS selectors when automating tasks. However, XPath supports some more advanced features for locating text content.
Can you use both XPath and CSS Selectors in one project?
Yes, you can use both XPath and CSS selectors in the same project. Tools like Selenium and Playwright support multiple locators. Sometimes, this is even recommended, as it allows you to leverage the strengths of both locators. However, one locator, usually CSS selectors, still needs to be chosen as the primary one.

Author
Marijus Narbutas
Senior Software Engineer
With more than seven years of experience, Marijus has contributed to developing systems in various industries, including healthcare, finance, and logistics. As a backend programmer who specializes in PHP and MySQL, Marijus develops and maintains server-side applications and databases, ensuring our website works smoothly and securely, providing a seamless experience for our clients. In his free time, he enjoys gaming on his PS5 and stays active with sports like tricking, running, and weight lifting.
Learn More About Marijus Narbutas