A Comprehensive XPath Locators Cheat Sheet

Master the syntax, expressions, functions, and various operators of XPath with a cheat sheet by DogQ, and enhance your automation testing and web scraping skills.

In the dynamic world of software testing, XPath stands out as a powerful tool for navigating through the XML structure of a webpage, making it indispensable for both developers and testers.

At DogQ, we understand the importance of efficient and accurate testing, especially when using no-code tools. Whether you’re a seasoned tester or just starting out, our XPath Cheat Sheet is designed to simplify your testing process by providing you with the essential XPath queries and patterns you need to quickly find elements without writing extensive code.

This guide will serve as your quick reference to make your automated testing tasks easier and more effective. Let’s dive into the world of XPath and explore how it can enhance your no-code testing capabilities at DogQ.

Table of contents:

What is XPath?

💡
XPath, which stands for XML Path Language, is a query language that allows you to select nodes from an XML document. Essentially, it’s used to navigate through the elements and attributes in an XML structure, which includes HTML pages. XPath performs this task by using a non-XML syntax that helps identify and process the elements within the XML document based on a set of rules or patterns.

Think of XPath as a roadmap for a website’s underlying code; it helps testers and developers pinpoint exactly where they want to go within the document’s structure without having to sift through all the content manually. This is particularly useful in automated testing, where specific elements need to be targeted quickly and accurately to ensure the tests are effective. XPath uses a straightforward path notation to point to these elements, which can include tags, attributes, and even text within the tags.

With XPath, you can also use various functions to refine your search, perform calculations, and even handle strings and date values, making it an extremely versatile tool in the realm of web development and testing.

XPath Types: Absolute vs. Relative

When working with XPath to locate elements within an XML or HTML document, you can take two main approaches: absolute XPath and relative XPath. Both are used to form paths that lead to specific elements, but they do so in distinctly different ways.

Absolute XPath

💡
Absolute XPath starts from the very root of the document and follows a path down to the desired element, detailing every single step along the way. It begins with a single forward slash (/), which signifies the root node and continues to detail the entire path to the element. 

For example, an absolute XPath might look something like this: ‘/html/body/div/table/tbody/tr[3]/td[2]/input’. This path points directly to an input element, but it’s also fragile; if any part of the path changes (such as an additional ‘div’ or ‘table’), the XPath will no longer locate the element correctly.

The drawback of writing Absolute XPath is length and maintainability. If there is a removal or inclusion of a new element in the DOM within the absolute XPath already written, then the XPath expression will break and has to be rewritten again.

Relative XPath

💡
Relative XPath, on the other hand, starts from anywhere within the document and typically begins with a double forward slash (//), which means it can match any element in the document that fits the criteria specified after the slashes.

For example, //div[@class=‘username’]/input would find any ‘input’ element that is a descendant of a ‘div’ with a class of ‘username’, no matter where it appears in the document. This type of XPath is more flexible and less likely to break if the document’s structure changes, as it doesn’t rely on a fixed path from the root.

💡
Both absolute and relative XPath have their uses. Absolute XPath can be useful when you are certain that the structure of the document will not change, and you need to pinpoint an element very specifically. Relative XPath is more advantageous in environments where the document’s structure may vary, allowing for more dynamic and robust testing scenarios.

In the following text, we present comments on XPath from our leading QA specialist, Egor Nedelko:

XPath Syntax

XPath expressions utilize a specialized syntax designed to navigate and query XML documents. This syntax comprises a blend of elements, functions, operators, and axes, which collectively help to pinpoint the elements you wish to target. Each component plays a role in forming queries that can precisely locate and manipulate data within the document, making XPath a powerful tool for web developers and testers alike.

Basic XPath Syntax

XPath provides a set of basic syntax elements that are essential for navigating and querying XML documents effectively. Each element serves a specific function in the XPath query, enabling precise targeting and manipulation of the document structure. Below is an overview of key XPath symbols and their roles in selecting nodes, attributes, and sequences within an XML or HTML document. Understanding these elements will enhance your ability to write robust and flexible XPath expressions for your testing needs.

  1. ‘*’ — Selects any element;
  2. ‘[ ]’ — Finds a specific element, example: //li[1];
  3. ‘node_name’ — Selects all nodes with the specified node name, examples include div, p, etc.;
  4. ‘/’ — Searches from the root node of the HTML document;
  5. ‘//’ — Searches for nodes anywhere in the document from the current node that matches the selection, regardless of their location;
  6. ‘.’ — Selects the current node;
  7. ‘..’ — Selects the parent of the current node;
  8. ‘@’ — Used to select a specific attribute. Example: //p[@value=”2008”].

XPath Selectors

💡
XPath selectors are powerful tools that allow you to pinpoint and interact with specific parts of an XML document with high precision. These selectors can be used to find nodes, attributes, or even specific strings, depending on your needs.

By mastering XPath selectors, testers and developers can ensure their queries are both efficient and precise, making automated testing more robust. Below, you’ll find a comprehensive list of commonly used XPath selectors and a brief explanation of each, helping you to navigate XML structures effectively.

Common XPath Selectors and Their Uses

Node Selection

  • ‘nodename’- selects all nodes with the given name. For example, ‘//div’ selects all ‘<div>’ elements;

Attribute Selection

  • ‘@attrname’- selects nodes that have a specific attribute. For example, ‘//@id’ selects all elements with an ‘id’ attribute;

Wildcard

  • ‘*’- selects all elements within the current node. For example, ‘//*’ selects all elements in the document;

Predicate

  • ‘[expression]’- uses conditions to select specific nodes. For example, ‘//input[@type=‘text’]selects all ‘<input>’ elements that have a type attribute with a value of ‘text’;

Positional Selectors

  • ‘[position]’- selects nodes at a specific position. For example, ‘//tr[1]’ selects the first ‘<tr>’ element;
  • ‘last()’ - selects the last node of the specified node set. For example, ‘//(div[last()])’ selects the last ‘<div>’ element;

Path Operators

  • ‘/’ - direct child operator. For example, ‘/html/body’ selects the body element directly under HTML;
  • ‘//’ - any descendant operator. This allows the selection of nodes anywhere in the document that match the selector, irrespective of their exact location. For example, ‘//body//div’ selects all ‘<div>’ elements anywhere under the ‘<body>’;

Current and Parent Node

  • ‘.’ - represents the current node. This is useful in predicates and other expressions where the context node is implied;
  • ‘..’ - Selects the parent of the current node. Useful for moving up in the XML hierarchy;

Attribute Value Selection

  • ‘[@attr=‘value’]’ - selects nodes where the attribute matches a specific value. For example, ‘//input[@name=‘username’]’ selects ‘<input>’ elements with a ‘name’ attribute of ‘username’.

By utilizing these selectors, you can effectively tailor your XPath expressions to target exactly what you need in an XML document, enhancing both the performance and reliability of your automated tests.

XPath Axes Cheat Sheet

XPath axes provide a powerful way to navigate the relationships between nodes in an XML document. These axes allow you to specify node sets relative to a current node, facilitating complex document traversals. This chapter will explain the most commonly used XPath axes and how each one can be utilized to access different parts of an XML structure effectively.

List of Common XPath Axes and Their Descriptions

  1. ‘ancestor’ - selects all ancestors (parent, grandparent, etc.) of the current node, up to the root node;
  2. ‘ancestor-or-self’ - selects all ancestors of the current node and also the node itself;
  3. ‘descendant’ - selects all descendants (children, grandchildren, etc.) of the current node;
  4. ‘descendant-or-self’ - selects the current node and all of its descendants;
  5. ‘following’ - selects everything in the document after the closing tag of the current node;
  6. ‘following-sibling’ - selects all siblings after the current node;
  7. ‘namespace’ - selects all namespace nodes of the current node;
  8. ‘parent’ - selects the parent of the current node;
  9. ‘preceding’ - selects all nodes that appear before the current node in the document, excluding ancestor nodes;
  10. ‘preceding-sibling’ - selects all siblings before the current node;
  11. ‘self’ - selects the current node itself;
  12. ‘child::*’ - selects all direct children of the current node;
  13. ‘child::note’ - selects all note nodes that are direct children of the current node;
  14. ‘attribute::*’ - selects all attributes of the current node;
  15. ‘child::*/child::heading’ - selects all direct children (i.e., “grandchildren”) of the current node that are heading nodes;
  16. ‘last()’ - selects the last element in the node set.

XPath Operators Cheat Sheet

XPath operators are special characters or keywords used in XPath expressions to perform comparisons or logical operations. These operators allow you to refine your search queries, making it possible to select nodes based on specific conditions or combine multiple conditions. Below, we explore the most commonly used XPath operators and provide examples to illustrate how each one is used in practice.

Common XPath Operators and Examples

  • ‘=’ - equal to, example: ‘//book[price=19.95]’, selects all <book> elements with a price of 19.95;
  • ‘!=’ - not equal to, example: ‘//book[price!=19.95]’, it selects all <book> elements where the price is not 19.95;
  • ‘<’ - less than, example: ‘//book[price<20]’, it elects all <book> elements with a price less than 20;
  • ‘<=’ - less than or equal to, example: ‘//book[price<=20]’, it elects all <book> elements with a price less than or equal to 20;
  • ‘>’ - greater than, example: ‘//book[price>20]’, it selects all <book> elements with a price greater than 20;
  • ‘>=’ - greater than or equal to, example: ‘//book[price>=20]’, it selects all <book> elements with a price greater than or equal to 20;
  • ‘and’ - logical AND, example: ‘//book[price>=10 and price<=20]’, selects all <book> elements with a price between 10 and 20 inclusive;
  • ‘or’ - logical OR, example: ‘//book[price<10 or price>20]’, selects all <book> elements with a price less than 10 or greater than 20;
  • ‘not’ - logical NOT, example: ‘//book[not(price=20)]’, selects all <book> elements that do not have a price of 20.

These operators are used for crafting effective XPath queries that can precisely target elements based on specific criteria or conditions within XML documents.

XPath Functions Cheat Sheet

XPath functions allow for complex querying and manipulation of an XML document’s content, making data extraction more flexible and powerful. These functions can perform a wide range of operations, from simple text extraction to complex calculations and string manipulations. Below, we explore some commonly used XPath functions along with examples to illustrate their utility.

Common XPath Functions and Examples

  • ‘text(’ - returns the text content of the <title> element, example: ‘//title/text()’;
  • ‘count()’ - returns the number of <book> elements in the document, example: ‘count(//book)’;
  • ‘normalize-space()’ - removes leading, trailing, and redundant intermediate spaces from the text of the <title> element, for example: ‘normalize-space(//title)’;
  • ‘starts-with(x, y)’ - checks if the <title> element’s text starts with the word “Data”, example: ‘starts-with(//title, ‘Data’)’;
  • ‘contains(x, y)’ - checks if the <description> element contains the phrase “machine learning”, example: ‘contains(//description, ‘machine learning’)’;
  • ‘last()’ - returns the last <book> element in the document, example: ‘(//book)[last()]’;
  • ‘position()’ - returns the third <book> element in the document, example: ‘(//book)[position() = 3]’;
  • ‘name()’ - returns the name of the first element in the document, for example: ‘name(//*[1])’;
  • ‘sum()’ - sums up the values of all <price> elements within <book> elements, example: ‘sum(//book/price)’;
  • ‘string()’ - converts the title of the <book> to a string, for example: ‘string(//book/title)’;
  • ‘lower-case()’ - converts the text of the <title> element to lowercase, example: ‘lower-case(//title)’;
  • ‘@attribut’ - selects the value of the isbn attribute of <book> elements, for example: ‘//book/@isbn’;
  • ‘concat()’ - concatenates the first and last names of authors, separated by a space, for example: ‘concat(//author/firstName, ‘ ’, //author/lastName)’;
  • ‘string-length()’ - returns the length of the text of the <title> element, example: ‘string-length(//title)’;
  • ‘substring()’ - returns the first 10 characters of the <title> element’s text, example: ‘substring(//title, 1, 10)’.

These XPath functions are instrumental for any XML data manipulation and querying task, providing the necessary tools to extract and process data effectively and efficiently.

XPath Expressions Cheat Sheet

XPath expressions are the core components of the XPath language. They are crafted to specify a path through an XML document, aiming to locate particular nodes or retrieve values. An XPath expression comprises a sequence of location steps, which are typically separated by slashes. These expressions can be enriched with predicates, functions, and various operators to refine and target specific data with precision.

Examples of XPath Expressions

  1. ‘/div/a[1]’ - selects the first anchor element within the <div> element;
  2. ‘/div/a[last()]’ - selects the last anchor element within the <div> element;
  3. ‘/div/a[last()-1]’ - selects the second-last anchor element within a <div> element;
  4. ‘/div/a[position()<3]’ - selects the first two anchor elements within a <div> element;
  5. ‘//a[@class]’ - selects all anchor elements that have a class attribute;
  6. ‘//a[@class=‘btn’]’ - selects all anchor elements where the class attribute equals ‘btn’;
  7. ‘/div/h1[1]/a’ - selects all anchor elements within the first <h1> element that are children of the <div> element;
  8. ‘/div/h1/a[1]’ - selects the first anchor element that is a child of any <h1> within a <div> element.

These examples showcase how XPath expressions are used to effectively navigate through and select specific parts of an XML document based on varied criteria.

Mastering XPath for Effective XML Navigation

Throughout this guide, we’ve explored the fundamental aspects of XPath, from its syntax and types to the detailed use of axes, operators, functions, and expressions. XPath is an indispensable tool in the toolkit of developers and testers who work with XML documents in Selenium-like tools, offering precise mechanisms for locating and manipulating nodes based on specific criteria.

Understanding and utilizing XPath expressions effectively allows for efficient data retrieval and manipulation, enabling more dynamic and robust applications. Whether modifying an existing XML structure or crafting new data queries, the flexibility and power of XPath can significantly enhance your ability to handle XML data.

As we’ve seen through various examples, mastering XPath not only improves your workflow but also deepens your understanding of how XML documents are structured and interconnected. With this knowledge, you are now better equipped to tackle complex data challenges and leverage the full potential of XML in your automated testing projects.

And if you need any help with our no-code DogQ testing tool, or need some advice or guidance, feel free to contact us – our specialists are ready to help you out! We’re here to make testing available for everyone!


Latest Posts:

Top 10 Automated Frontend Testing Tools. A comprehensive guide to automated testing tools from DogQ specialists.

Automated UI Testing for WordPress with DogQ. Discover the benefits of automated UI testing for WordPress and get a detailed guide.

The Most Common Types of Software Bugs. Discover the most common types of software bugs and get professional recommendations.


20 Top Test Automation Tools. We have compiled an ultimate list of top test automation tools.

14 Best Codeless Test Automation Tools in 2024. A complete guide on the 14 best codeless test automation tools with all their pros and cons.

10+ Best UI Automation Testing Tools. We delve into the depths of UI automation testing, and highlighting some of the best tools available in the market.