Table of Contents Show The Selenium framework helps us interact with WebElements in DOM (Document Object Model). But, you’ll need web locators to proceed. Luckily, a plethora of Selenium web locators are available out there. You might crave a Selenium locators cheat sheet to help. Only question is: which is the right one for the best interaction with WebElements in DOM? Selenium provides a wide range of options for web locators, such as ID, Name, XPath, LinkText, and Tag Name. XPath is one of the most commonly used. XPath or XML Path Language is an expression language that supports the query or transformation of XML documents. It can easily traverse through DOM elements and attributes. If you plan to use the XPath web locator to create test automation scripts, this XPath cheat sheet is for you. Our Selenium XPath cheat sheet will help you learn and remember XPath syntax, expressions, and much more. Click here to download our free XPath Cheat Sheet PDF. Let’s begin! XPath Cheat Sheet For Quick ReferencesThis XPath cheat sheet comes in handy when you need to have a quick look at XPath syntax and various other aspects of XPath locators. First, let’s explore exactly what the XPath web location in Selenium means. What is XPath Web Locator in Selenium?XPath uses the path-like syntax that helps us identify and navigate the nodes found in XML and HTML documents. In other words, it uses non-XML syntax that makes it flexible to address various parts of an XML document. Moreover, XPath follows the XSLT(eXtensible Stylesheet Language Transformations) standard, which is commonly used for navigating the WebElements and attributes. DOM is essential to navigating through HTML documents. It works as a map containing all WebElements and the one you are looking for. You can find the desired WebElements from DOM using the appropriate web locator. Different Types of XPath LocatorsThere are two ways to locate the desired WebElement in the DOM. One is through the absolute path, and the other is through the relative path. In this section of our XPath cheat sheet, we shall look at different ways of using an XPath locator to find the desired WebElement in the DOM. 1. Absolute XPathAbsolute path specifies the complete path from the root element to the element you want to use. But, you might face issues using the absolute path. If there is any change made within the path of the element, it results in XPath failure. Whenever you use the absolute path, you must begin the XPath using the single forward-slash (/). This indicates you’re selecting the element from the document’s root node. Syntax:
Example:
To locate an element, you can right-click on the web element and click on Inspect. You will then see the Elements tab, where you can write the locator. In this case, we started from the HTML tag and traversed one by one to the div, containing the tag up to the final img tag. Even though it seems simple, the common disadvantage is that even a small change in the DOM structure will lead to several automation failures. 2. Relative XPathUnlike the absolute path, the relative XPath refers to an element that we want to locate in a specific location. In this case, the element is positioned relative to its actual position. To use the relative path, you must specify the double forward-slash (//) at the beginning. Mostly, the relative XPath is preferred for Selenium automation testing. If there is any change to the page design or the DOM hierarchy, the existing XPath selector won’t be impacted. Syntax: //tagname[@attribute='value'] XPath Syntax In order to select the nodes in an HTML document, XPath uses this path expression:
Here are some popular Path expressions for selecting a node in an XML document: Expression / XPath Description node Select all elements with the name / Select from the root node // Select elements in the document from the current element that matches the selection (no matter where they are) . Select the current node .. Select the parent of the current node element. @ Select the attributes XPath ExpressionsXPath expressions are patterns used to select a set of nodes and carry out transformations. XPath uses the path expression for selecting nodes from XML and HTML documents. Syntax:
Example: <?xml version="1.0"standalone="yes"?> You’ll find theaxis and corresponding steps below. Axis // / Step ul a[@id=’link’] Prefixes ExpressionWe can use prefixes in XPath at the beginning of the XPath expression: Expression Example Description // //p[@class=’footer’] Select paragraph tag from anywhere in the DOM / /a Find all anchor (a) tags from the given node / /html/body/div Find all div, starting from root element Here are some examples of various steps available in XPath: XPath Description //div Select all div tags //[@id=’btn’] Select all elements with ID ‘btn’ //div[@name=’post’] Selecting all div elements with the name ‘post’ //a/text() Gives the text of all the anchor tag(s) //a/@href Gives href value of anchor tag Need More Help? Checkout This CourseSelecting NodesThe following table includes XPath expressions for selecting nodes or WebElements. XPath Description div Selects all div elements /div Selects div element from the root element div/tr Select all tr elements that are children of div //tr Select all tr elements anywhere in the document div//tr Selecting all tr elements that are children of div anywhere in the document //@class Select all class attributes Predicates for Finding NodesYou can use predicates in XPath to locate a specific node containing a designated value. They’re enclosed in square brackets, as shown in the table below. These predicate identifiers return the boolean values (true or false). You can even use the relational and boolean operators with them. XPath Description /div/a[1] Selects the first anchor element within the div element /div/a[last()] Selects the last anchor element within the div element /div/a[last()-1] Selects the second-last anchor element within a div element /div/a[position()<3] Select the first two anchor elements within a div element //a[@class] Select all anchor elements with class attribute //a[@class=’btn’] Select all anchor elements with class attribute and value ‘btn’ /div/h2[1]/a Select all anchor elements within h2 that are children of the div element /div/h2/a[1] Select all anchor elements that are children of h2 within a div element For example: Expression Description element_name[N] Opening and closing square bracket referring to a specific element sequence number (array sequence). empinfo/employee[2] Second Child of child element; Selects the second employee of empinfo element. empinfo/employee[2]/name Sequence of child element; Selects name element of second employee element of empinfo element. element_name[@attribute_name] empinfo/employee[@id] Selects element with attribute Selects all employee elements with a given id attribute. element_name[@attribute_name=value] empinfo/employee[@id=2] Selects element with specified attribute value; Finding employee elements with given attributes and values. Matching only those elements whose attribute and value are specified in the XPath expression. empinfo/employee[@id=2][2] Selects all employee elements of given attribute and value. At last, select only the second employee element. empinfo/employee[1][@id=1] Selects the first employee element with the given attribute and value. //designation[@discipline and @experience] Selects all the designation elements with given first and second both attributes. //designation[@discipline or @experience] //designation[@discipline | @experience] Selects all the designation elements with either first or second, both attributes. Chaining OrderThe meaning of XPath changes with the change in order. For example: a[1][@href=’/’] and a[@href=’/’][1] are different. IndexingYou have to use [] for indexing in XPath, where [] contains a number that specifies the node you want to select. You can also use functions for indexing in XPath, such as last(), position(), and others, to specify the index of the elements. For example: //a[1] Select the first anchor tag //a[last()] Select the last anchor tag //ul/li[2] Select the second li tag (a child of ul tag) //ul/li[position()=2] Select second li tag which is a child of ul tag //ul/li[position()>1] Select li tag which is not a first child of ul tag Expressions for Selecting Unknown Nodes (Wildcards)You can use the wildcard with the XPath locator to find the unknown HTML document elements. * Matches any HTML element @* Matches any attribute of an element node() Matches any kind of element /div/* Select all children of a div element //* Select all elements in the HTML document //a[@*] Select all anchor elements with any attribute . Matches any HTML element .. Refers to a parent context node / Refers to a root node // Refers to a node anywhere within the document * Refers to all elements that are child of the context node | or Refers to an OR condition combine expression either first expression or second expression and Refers to a condition and combining expression text() Selects all text node children of the current element. Expressions for Selecting Several PathsYou can use the ‘|’ operator in the XPath expression to select several paths. Here’s how you use the ‘|’ operator: //div | //a Select all div and anchor elements in the HTML document //div/h2 | //div/a Select all h2 and anchor elements within a div element XPath AxesThere are 13 axes available in XPath specifications. These axes represent the relationship between the context node or referred node. 13 axes are defined in XPath, enabling you to search different node parts in an XML document from the current context node or the root node. XPath Axes select the nodes from the context node within the document. Axes example and Node test AxesName ::= 'self' |'child' | 'descendant' | 'descendant-or-self' | 'parent' | 'ancestor' | 'ancestor-or-self' | 'attribute' | 'following' | 'following-sibling' | 'preceding' | 'preceding-sibling' | 'namespace'
Syntax: AxesName::node[predicate] Where:
Example:
Node TestNode test is a part of XPath expression for finding nodes in XML documents. Select Axis Description //name/self::* Selects the name context node child::* Selects all child nodes of the context node. child::node() Selects all child nodes of the context node child::empinfo Selects all child elements of empinfo node //employee/descendant::* Selects all descendants of the employee node //descendant::employee Selects all descendants of the employee node in context node. //employee/descendant-or-self::* Selects all descendants of the employee nodes and context node itself. //descendant-or-self::employee This axis selects all descendant of employee node with context node itself. Ancestors//employee/ancestor::* Select all ancestor nodes of the employee node //ancestor::name Select all ancestors of the name node in context node //employee/ancestor-or-self::* Select all ancestors of the employee nodes and the context node itself. //name/ancestor-or-self::employee Select all ancestors of the name node with the context node itself //name/parent::* Select the parent node of the name context node //name/parent::employee Return result node if employee node is parent node of the context node; otherwise no node found. //attribute::id Select all nodes with id attribute //attribute::* Select all nodes with any attribute //employee[@id=1]/following::* Select all nodes (with child nodes) after the context node //employee[@id=1]/following-sibling::* Select all sibling nodes after the context node //employee[@id=3]/preceding::* Select all nodes (with child nodes) before the context node //employee[@id=3]/preceding-sibling::* Select all sibling nodes before the context node For example:
Where:
XPath OperatorsAn XPath expression can return a number, boolean (true or false), node-set(div,a,li), or string. You can use various operators to manipulate the values returned by an XPath expression. Here are the various operators used in the XPath expression: Operator Description | Computes two node-sets. + Addition Operator - Subtraction Operator * Multiplication Operator div Division Operator = Equal Operator != Not Equal Operator < Less than Operator <= Less than or Equal to Operator > Greater than Operator >= Greater than or Equal to Operator or Or Operator and And Operator mod Modulus (Division Remainder) There are five different types of XPath Operators, listed below:
Comparison OperatorsComparison operators compare two different values. Here are examples of various comparison operators used in an XPath expression: Operator Description = Specifies equals to != Specifies not equals to < Specifies less than > Specifies greater than <= Specifies less than or equals to >= Specifies greater than or equals to In the below example, we create a table of elements containing attribute id and child <firstname>,<lastname>, <nickname>, and <salary> by iterating over each employee. It checks the salary to be greater than (>) 25000 and then prints the details. Employee.xml
Employee.xsl
Boolean OperatorsThis type of operator returns true or false as result. The following are different boolean operators in XPath: Operator Description and Specifies both conditions must be satisfied or Specifies any one of the conditions must be satisfied not() Specifies a function to check conditions not to be satisfied In this example, we create a table of elements with its attribute id and child <firstname>,<lastname>, <nickname>, and <salary>.The example checks id to be either 001 or 003, then prints the details. Employee.xml
Employee.xsl
Number Operators and FunctionsThe following describes various number operators you can use an in Xpath expression: Operator Description + Addition operation - Subtraction operation * Multiplication operation div Division operation mod Modulo operation Here are some functions you can perform on XPath expressions: Function Description ceiling() Returns the smallest integer larger than the value provided floor() Returns the largest integer smaller than the value provided round() Returns the rounded value to the nearest integer sum() Returns the sum of two numbers In this example, we create a table of <employee> element with its attribute id and child <firstname>,<lastname>, <nickname>, and <salary>. It calculates the salary of the employees, then displays the result. Employee.xml
Employee.xsl
String FunctionsHere are various string functions that help you carry out XPath expression tasks:
In this example, we create a table of <employee> elements with their names and length of names, by iterating over each employee. It calculates the length of the employee name after concatenating firstname and lastname, then displays the employee details. Example.xml
Example.xsl
Node FunctionsThe following table highlights various node operators, along with their descriptions: Operator Description / Select node under a specific node. // Select node from root node. [...] Check node value. | Unifies two node sets. The following is the list of the node functions used in XPath expressions. Function Description node() Selects all kinds of nodes processing-instruction() Selects nodes processing instructions text() Selects a text node name() Provides node name position() Provides node position last() Selects the last node relative to current node comment() Selects nodes that are comments In this example, we create a table of <employee> elements with their details by iterating over each employee. It calculates the position of the student node, then displays employee details with serial numbers. Employee.xml:
Employee.xsl:
XPath SelectorsWith the help of the XPath selectors, you can select only a specific part of your HTML document specified by the XPath elements. XPath has many different types of selectos. Descendent SelectorsDescendant selectors represent all the current node’s children, and all children of each child, etc. These selectors do not include attribute and namespace nodes. The parent of an attribute node is its element node, whereas attribute nodes are not the offspring of their parents. div //div Select all div elements div h2 //div//h2 Select all h2 within a div element ul > li //ul/li Select all li elements which are children of ul div > p > a /div/p/a Select all anchor tags within paragraph tag of div element div > * //div/* Select all elements in div tag :root / Select root element of the DOM :root > body /body Select body tag Attribute SelectorsThe XPath attribute selector matches elements based on the presence or value of a given attribute. Element Xpath Description #id //*[@id=”id”] Select all elements with matching ID attribute .class //*[@class=”class”] Select all elements with matching class attribute a[rel] //a[@rel] Select all anchor tag(s) with rel attribute. a[href^=’/’] //a[starts-with(@href, ‘/’)] Select all anchor tag(s) with href starting with ‘/’ a[href$=’txt’] //a[ends-with(@href, ‘.txt’)] Select all anchor tag(s) with href ending with ‘.txt’ a[rel~=’details’] //a[contains(@rel, ‘details’)] Select all anchor tag(s) with rel value ‘details’ input[type=”password”] //input[@type=”password”] Select all input tag(s) of type password a#btn[for=”XYZ”] //a[@id=”btn”][@for=”XYZ”] Select all anchor tag(s) with ‘btn’ ID linked with XYZ Order SelectorsYou can use order selectors in XPath to retrieve list elements. Element XPath Description ul > li:first-of-type //ul/li[1] Select first li tag that is a child of ul ul > li:nth-of-type(2) //ul/li[2] Select second li tag that is a child of ul li#id:first-of-type //li[1][@id=”id”] Select first li with id value “id” ul > li:last-of-type //ul/li[last()] Select last li that is a child of ul a:first-child //*[1][name()=”a”] Select first child of anchor tag a:last-child //*[last()][name()=”a”] Select last child of anchor tag SiblingsIn Selenium WebDriver, you can retrieve a WebElement that is a sibling to a parent element. Here’s how to fetch elements using siblings in Selenium WebDriver: Element XPath Description h2 ~ ul //h2/following-sibling::ul Select all ul tags following sibling of h2 tag h2 ~ #id //h2/following-sibling::[@id=”id”] Select all elements with ID value “id” that are siblings of h2 h2 + ul //h2/following-sibling::ul[1] Select first ul tags following sibling of h2 Different OperatorsThere are other operators in XPathto locate elements: Operators XPath Description Not Operators //p[not(@id)] Select all paragraph tag(s) with attributes not matching id Text match //button[text()=”Submit”] Select button with text input “Submit” Text match (substring) //button[contains(text(),”pass”)] Select button that has string ‘pass’ present in it Arithmetic //product[@price > 3] Select price with value > 3 Has children //ul[*] Select ul with any number (or type) if it has children Has children (specific) //ul[li] Select ul with any number and li tag present as a child logic //a[@name or @href] Select all anchor tag(s) with the name and href attribute Union (joins results) //a | //div Union of a and div tags Contextual SelectorsLocators Description //img image element //img/*[1] first child of element img //ul/child::li first child 'li' of 'ul' //img[1] first img child //img/*[last()] last child of element img //img[last()] last img child //img[last()-1] second last img child //ul[*] ul' that has children Attribute SelectorsLocators Description //img[@id='myId'] image element with @id= 'myId' //img[@id!='myId'] image elements with @id not equal to 'myId' //img[@name] image elements that have name attribute //*[contains(@id, 'Id')] element with @id containing //*[starts-with(@id, 'Id')] element with @id starting with //*[ends-with(@id, 'Id')] element with @id ending with //*[matches(@id, 'r')] element with @id matching regex ‘r’ //*[@name='myName'] image element with @name= 'myName' //*[@id='X' or @name='X'] element with @id X or a name X //*[@name="N"][@value="v"] element with @name N & specified @value ‘v’ //*[@name="N" and @value="v"] element with @name N & specified @value ‘v’ //*[@name="N" and not(@value="v")] element with @name N & not specified @value ‘v’ //input[@type="submit"] input of type submit //a[@href="url"] anchor with target link 'url' //section[//h2[@id='hi']] returns <section> if it has an <h2> descendant with @id= 'hi' //*[@id="TestTable"]//tr[3]//td[2] cell by row and column //input[@checked] checkbox (or radio button) that is checked //a[@disabled] all 'a' elements that are disabled //a[@price > 2.50] a' with price > 2.5 XPath MethodsHere are some of the variousXPath methods: Locator Explanation //table[count(tr) > 1] Return table with more than 1 row //*[.="t"] Element containing text 't' exactly //a[contains(text(), "Log Out")] Anchor with inner text containing 'Log Out' //a[not(contains(text(), "Log Out"))] Anchor with inner text not containing 'Log Out' //a[not(@disabled)] All 'a' elements that are not disabled Math MethodsLocator Explanation ceiling(number) Evaluates a decimal number and returns thesmallestinteger greater than or equal to the decimal number floor(number) Evaluates a decimal number and returns thelargestinteger less than or equal to the decimal number round(decimal) Returns the nearest integer to the given number sum(node-set) Returns the sum of the numeric values of each node in a given node-set String MethodsLocator Explanation contains(space-string, planet-string) Determines whether the first argument string contains the second argument string and returns boolean true or false concat(string1, string2 [stringn]*) Concatenates two or more strings and returns the resulting string normalize-space(string) Strips leading and trailing white-space from a string; replaces sequences of whitespace characters by a single space; returns the resulting string starts-with(spacetrack, space) Checks whether the first string starts with the second string and returns true or false string-length([string]) Returns a number equal to the number of characters in a given string substring(string, start [length]) Returns part of a given string substring-after(spacetrack, track) Returns the rest of a given string after a given substring substring-before(spacetrack, tra) Returns the rest of a given string before a given substring translate(string, ghj, GHJ) Evaluates a string and a set of characters to translate and returns the translated string Obtaining XPath using JQueryJQuery supports all basic kinds of XPath expressions. The major ones are listed below in this next section of our XPath cheat sheet! JQuery XPath XPath Description $(‘ul > li’).parent() //ul/li/.. Selects all ul elements that are parent of li tag $(‘li’).closest(‘section’) //li/ancestor-or-self::section Selects all anchor tags with href attribute $(‘p’).text() //p/text() Selects text within paragraph tags ConclusionWe’ve come to the end of our XPath cheat sheet. XPath is a commonly used web locator in Selenium. But to have an efficient XPath, you must depend on the document’s structure and the current position of the WebElement. We covered all the major aspects of the XPath locator in this exhaustive Selenium web locator cheat sheet. Take your work to the next level by having this nearby whenever you need it. Interested in learning more about Selenium WebDriver and finding an accompanying Selenium cheat sheet? Check out our Selenium WebDriver guide. Frequently Asked Questions1. What is an XPath Example?Imagine a bookstore with many books. Each book will have a different title, author, price, year of publication, and contents — all information stored in the bookstore's computer. One way data is transferred from the bookstore computer to our computer is through an XML file. An XML file contains data, and looks like this:
Note that the first line states the XML version. If you look at the XML file, its structure resembles a file cabinet. The name of the file cabinet is a bookstore. The file cabinet contains different files or different pieces of information — category, language, title, author, year, price, etc. The bookstore is known as the root element, or root node because all other information is within the bookstore. Each piece of information inside the root node is known as a node. The nodes are the names between the tags < > and </ >. In this XML file, the root node is a bookstore. The nodes are category, language, title, author, year, and price. 2. What is the Easiest Way to Find XPath?Here’s how to find XPath in the easiest way possible:
3. What is the Correct XPath Syntax?XPath contains the element’s path situated at the web page. The standard XPath syntax for creating XPath is:
// : Select current node. Tagname: Tagname of the particular node. @: Select attribute. Attribute: Attribute name of the node. Value: Value of the attribute. 4. How Do I Get XPath in HTML?If you’re using Chrome to find an XPath for an HTML element, you don’t need any extensions installed.
Note: This just copies the minimal XPath information. Firebug for Firefox can give you the full XPath information. |