Turn your manual testers into automation experts! Request a DemoStart testRigor Free

CSS Selector vs XPath: Your Pocket Cheat Sheet

What is a locator in Selenium?

Locators in Selenium are used to find a specific element in web pages. We can use them to find almost any part of a web page. Once we have a locator expression that uniquely identifies a specific web element, we can pass this to the WebDriver object and then use various built-in methods like click, send_keys, clear, etc., in Selenium to interact with that element.

It’s one of the foundational concepts in traditional test automation. A QA must learn about writing the best locator expressions to have a faster workflow. Most beginner automation engineers struggle to write the correct locator expression. By the end of this article, you will be able to write short, clean, and robust CSS and XPath expressions in the least time possible.

In this article, we will learn how to write clean expressions, i.e., XPath and CSS selectors, very quickly to have a smoother workflow. We will also learn about two beneficial browser extensions that automatically generate valid CSS selectors and XPath.

Different types of locators

Selenium supports eight different types of locators: className, name, id, tagName, linkText, partialLinkText, XPath and CSS selector.

Out of these eight selectors, className and tagName are rarely used because usually, in a production application, we will often find multiple locators in a given class or tag name. Even if we encounter a class or tag used for a unique locator, there is a high chance this would change in a future update. linkText and partialLinkText can be used on a case-to-case basis.

XPath and CSS selector are the most used element locators for the following common advantages:

  1. We don’t have to depend on a single class name or tag name, and we can leverage multiple ids and tags
  2. We can traverse from parent to child
  3. We can write robust expressions which can withstand front end changes

What is an XPath?

XPath, also sometimes referred to as XML path, is a query syntax for an XML schema. It is used in many programming languages like Java, C#, Python, JavaScript, etc.

XPath is used in XML schemas, which allows us to locate specific parts of the document. XPath expressions traverse through an XML document in a way that it can trace from the first node to any required element on a web page. We can use it for advanced search and validation purposes as well.

Advantages and disadvantages of XPath

  • Widely compatible with multiple programming languages.
  • Supports both XML and HTML attributes.
  • We can work with any node present in an XML document and use various conditions to pick the right locator.
  • XPath expressions return any number of results in DOM, including zero.
  • There is no need to traverse from the top node with an XPath expression. It works at any document level.
  • In a programming context, XPath expressions are not procedural; they are declarative. It is vital because a query optimizer must be free to use indexes or other structures to find results efficiently.
  • XPath allows bidirectional flow. Using an XPath, we can traverse both ways, i.e., from parent to child and child to parent, which is not possible in CSS.

XPath Syntax

Expression Description
node_name Select all nodes with this name
/ Select from the root node
. Select the current node
// Select nodes from the current node that match the selection
@ Select attributes
.. Select the parent of the current node
* Select any element node
@* Select any attribute node
node() Select any node

XPath also has predicates (always embedded in square brackets), that you can use to find any specific node, or a node with a certain value.

Expression Result
/audio/file[last()] Select the last audio file that is the child of an audio element
/audio/file[1] Select the first audio file
/audio/file[position()>4] Selects all audio files that are children of an audio file and have value 5 and above
//[@labeled] Select all elements with the labeled element
/audio/file/[price>9.99]/title Select all the title elements of the file element of the audio element with the value > 9.99


What is CSS Selector?

A CSS Selector is a string representation of different HTML tags, classes, attributes, and ids. It is an expression that lets us uniquely identify a web element in Selenium.

Advantages and disadvantages of CSS Selectors

  • Simple syntax since they include a single element in their structure.
  • Performance is the same or faster compared to XPath.
  • Easier to learn than XPath, easier to use.
  • CSS Selector only allows unidirectional flow. Using a CSS Selector, we can only traverse from parent to child but not from the child to parent, which is possible with XPath.

Automation scripts can handle most locators using both XPath and CSS selectors.

Best practices while writing locator expressions

Typically, CSS selectors are almost as powerful as XPath. However, some browsers might not fully support all of the CSS selectors you need. Another reason why you might want to use an XPath exclusively might be finding an element by moving back to the DOM (which only XPath would support). Using short and robust locators will ensure the script survives more incoming front-end changes. While writing a locator expression, be it XPath or CSS, we should consider the following points:

    • A locator expression must match the targeted element.
    • A locator expression must not match any other element in the DOM.
  • Don’t use any information that’s likely to change in the future.
  • Always keep the locator expressions short by using minimal required information.
  • Avoid using absolute expressions, for example:
      • Absolute XPath expression – /html/body/div[2]/div[1]/div/h4[1]/b/html[1]/body[1]/div[2]/div[1]/div[1]/h4[1]/b[1]
      • Absolute CSS expression –  html.body.div.p.div.a
      • The problem with absolute expression is if any one of the nodes changes, and in the event of adding more siblings to any node, they tend to break.
  • Use relative expressions instead, easy to write and more robust, for example:
    • Relative XPath expression –  //tagname[@attribute=‘value’]
    • Relative CSS expression – tagname[attribute=‘value’]

Cheatsheet for writing Selenium locators

Locator Type Syntax Example
XPath //tagname[@attribute=’value’] “//input[@name=’email’]”
CSS Selector tagname[attribute=’value’] “input[name=’email’]”
ID No syntax “id”
Name No syntax “name”
Class name No syntax “class-name”
Link text No syntax “link-text”
Partial link text No syntax “partial-text”
Tag name No syntax “tag-name”

We can pass the values from the example column into the following respective Selenium methods:

Where driver is WebDriver object in Selenium, sample code is in Python

driver.find_element_by_link_text(“Help Menu”)
driver.find_element_by_partial_link_text(“prime user”)

Standard expressions for writing XPath and CSS selectors

Customized XPath Locator Syntax Without Tag Name

Syntax: //tag_name[@attribute=‘value’]

// lets us transverse to a specific tag, and we can use attribute value to filter the right locator

Example: //tag_name[@name = ‘username’]

Customized CSS Selector Syntax Without Tag Name

Using the tag name in the CSS Selector expression is not mandatory. We can use attribute values and class names in square parenthesis.

Syntax: [attribute=’value’]

For example, [class=’error-msg’] returns a locator with class error-msg

We can also use * operator to find partial matches.

For example, [class*=’data-test’] returns all the locators with a class name, which starts with data-test.

Generating XPath based on text

Whenever we need to validate text on a web page, whether it’s a heading, name of a product, or an error message – the following syntax can be super useful:

Syntax: //tagname[contains(text(), ‘actual-text’)]

Example: //span[contains(text(),’Cart’)] will return the locator for Cart

Generating XPath by traversing tags

If there are multiple results for a specific tag, we can leverage parent tags:

Syntax: //tag_name[@attribute = ‘parent_tag/child_tag’]

Example: //div[@class=’product-action’]/apply_coupon

Creating a CSS Selector by traversing to the nth-child

Syntax: tagname:nth-child(x)

Example: div:nth-child(2)

Select Parent Locator from Child using XPath

Syntax: XPATH/parent::tagname

Example: //*[title=”data-test”]/parent::div

Generating CSS Selector from Tag and Class Name

Replace spaces with period(.) to use more than one class name

Syntax: tagname.classname

Example: input.search-bar

Best browser extensions to generate locator expressions automatically.

You can use the above cheat sheet to write locator expressions like XPath and CSS selector for any web element. In a real-world automation project, we will work with multiple web pages, which requires a QA Engineer to write hundreds of locators. This becomes very tedious and frustrating very quickly. You can use browser extensions that are intelligent enough to automate this.

1. SelectorsHub

Using the SelectorsHub extension, you can generate CSS and XPath expressions in less than 5 seconds. SelectorsHub is a Chrome extension that auto-suggests different versions of locator expressions by letting the user choose various attributes, text, etc.

2. ChroPath

ChroPath is another helpful plugin that generates locator expressions automatically. ChroPath is well known for developing XPath expressions. Using ChroPath, we can right-click on any locator and copy its XPath from the menu instantly.

Both SelectorsHub and ChroPath support all major browsers. With the help of browser extensions, you can instantly generate most locator selector expressions. In some cases though, these automatic extensions may generate lengthy locators. We can use the above cheat sheet to optimize such locators.


So which type of locator expressions do you prefer, XPath or CSS Selectors?

Or, you can simply switch to testRigor for all of your end-to-end test automation needs, and forget about CSS Selectors, XPath, and pretty much everything else you’ve just learned.

But how?

testRigor is a no code automation tool, where you relate to any element on the screen from an end-user’s perspective. You don’t use any implementation details such as locators, which also makes test indifferent to any changes or updates in this regard.

The whole command of your automated test will look like this:

enter "149 New Montgomery" into "Address" in the "From" section


check that table at the row containing stored value "generatedId" and column "Status" contains "Approved"

Looks clean, isn’t it? Makes all of your tests to look extremely neat, and easy to maintain. It also means that even if the entire underlying programming framework changes, the tests will still pass – in case the UI stays the same.

Related Articles

What is BDD 2.0 (SDD)?

The ability to document test scripts in the exact way the user intends has always been the ultimate dream for testers. Until the ...

Top 59 Test Automation Tools to Choose from in 2024

The quote precisely mentions the most important action point during software testing. When there is late bug detection in a ...