Turn your manual testers into automated 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 Selector 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 selector expressions, i.e., XPath and CSS, very quickly to have a smoother workflow. We will also learn about two beneficial browser extensions that automatically generate valid CSS and XPath selectors.

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 or 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.

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.

Our 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 where 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 selector expression must match the targeted element.
  • A locator selector expression must not match any other element in the DOM.
  • Don’t use information that’s likely to change in the future.
  • Always keep the locator expressions short by using minimal required information.
  • Avoid using absolute expressions:
    • Abs_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]
    • Abs_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:
    • rel_xpath = //tagname[@attribute=‘value’]
    • rel_css = 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_xpath(“//input[@name=’password’]”)
driver.find_element_by_css_selector(“input[name=’password’]”)
driver.find_element_by_id(“3qwetu”)
driver.find_element_by_name(“coupon”)
driver.find_element_by_class_name(“btn-success”)
driver.find_element_by_link_text(“Help Menu”)
driver.find_element_by_partial_link_text(“prime user”)
driver.find_element_by_tag_name(“div”)

Standard expressions for writing CSS and XPath locators

Customized XPath Locator 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’)]

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

Creating 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 selector expressions automatically.

You can use the above cheat sheet to write locator selector expressions like XPath and CSS selector expressions 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 Selector expressions by letting the user choose various attributes, text, etc.

2. ChroPath

ChroPath is another helpful plugin that generates locator selector 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.

Conclusion

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. So the whole command will look like this:

click “Password”

This means that your UI test isn’t only very accurate, but it’ll also pass even if the whole underlying framework would change – unless the UI stays the same.