Xpath
Xpath
Xpath
First, let’s explore exactly what the XPath web location in Selenium means.
DOM is essential to navigate 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.
Absolute XPath
Absolute 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:
/html/body/div[x]/div[y]/
Example:
/html//div/div/div/div[1]/div/a/img
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.
Relative XPath
Unlike 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:
XPath=//tagname[@Attribute="Value"]
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 Expressions
XPath 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:
//tagname[@attribute='value']
Example:
Axis // /
Step ul a[@id=’link’]
Prefixes Expression
We can use prefixes in XPath at the beginning of the XPath expression:
XPath Description
//div Select all div tags
//[@id=’btn’] Select all elements with ID ‘btn’
Selecting Nodes
The 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
Selecting all tr elements that are children of div anywhere in the
div//tr document
//@class Select all class attributes
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/h1[1]/a Select all anchor elements within h1 that are children of the div element
/div/h1/a[1] Select all anchor elements that are children of h1 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 Sequence of child element;
]/name Selects name element of second employee element of empinfo element.
element_name[@at Selects element with attribute
tribute_name] Selects all employee elements with a given id attribute.
empinfo/employee[
@id]
element_name[@at Selects element with specified attribute value;
tribute_name=value Finding employee elements with given attributes and values.
]
empinfo/employee[ Matching only those elements whose attribute and value are specified in
@id=2] the XPath expression.
empinfo/employee[ Selects all employee elements of given attribute and value. At last,
@id=2][2] select only the second employee element.
empinfo/employee[1 Selects the first employee element with the given attribute and value.
][@id=1]
//designation[@disci Selects all the designation elements with given first and second both
pline and attributes.
@experience]
//designation[@disci Selects all the designation elements with either first or second, both
pline or attributes.
@experience]
//designation[@disci
pline |
@experience]
Chaining Order
The meaning of XPath changes with the change in order.
For example:
a[1][@href=’/’] and
a[@href=’/’][1] are different.
Indexing
You 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:
//div | //a Select all div and anchor elements in the HTML document
//div/h1 | //div/a Select all h1 and anchor elements within a div element
XPath Axes
There 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.
Syntax:
AxesName::node[predicate]
Where:
Example:
<?xml version="1.0" standalone="yes"?>
<empinfo>
<employee id="1">
<name>Opal Kole</name>
<designation discipline="web" experience="3 year">Senior
Engineer</designation>
<email>[email protected]</email>
</employee>
<employee id="2">
<name from="CA">Max Miller</name>
<designation discipline="DBA" experience="2 year">DBA
Engineer</designation>
<email>[email protected]</email>
</employee>
<employee id="3">
<name>Beccaa Moss</name>
<designation discipline="appdev">Application
Developer</designation>
<email>[email protected]</email>
</employee>
</empinfo>
Node Test
Node test is a part of XPath expression for finding nodes in XML documents.
For example:
Where:
XPath Operators
An 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.
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)
● Comparison operators
● Boolean operators
● Number operators or functions
● String functions
● Node operators or functions
Comparison Operators
Comparison 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
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?>
<class>
<employee id = "001">
<firstname>Abhiram</firstname>
<lastname>Kushwaha</lastname>
<nickname>Manoj</nickname>
<salary>15000</salary>
</employee>
<employee id = "002">
<firstname>Akash</firstname>
<lastname>Singh</lastname>
<nickname>Bunty</nickname>
<salary>25000</salary>
</employee>
<employee id = "003">
<firstname>Brijesh</firstname>
<lastname>Kaushik</lastname>
<nickname>Ballu</nickname>
<salary>20000</salary>
</employee>
<employee id = "004">
<firstname>Zoya</firstname>
<lastname>Mansoori</lastname>
<nickname>Sonam</nickname>
<salary>30000</salary>
</employee>
</class>
Employee.xsl
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/">
<html>
<body>
<h2>Employee</h2>
<table border = "1">
<tr bgcolor = "pink">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Salary</th>
</tr>
<xsl:for-each select = "class/employee">
<xsl:if test = "salary > 25000">
<tr>
<td><xsl:value-of select = "@id"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "salary"/></td>
</tr>
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Boolean Operators
This type of operators return 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
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?>
<class>
<employee id = "001">
<firstname>Abhiram</firstname>
<lastname>Kushwaha</lastname>
<nickname>Manoj</nickname>
<salary>15000</salary>
</employee>
<employee id = "002">
<firstname>Akash</firstname>
<lastname>Singh</lastname>
<nickname>Bunty</nickname>
<salary>25000</salary>
</employee>
<employee id = "003">
<firstname>Brijesh</firstname>
<lastname>Kaushik</lastname>
<nickname>Ballu</nickname>
<salary>20000</salary>
</employee>
<employee id = "004">
<firstname>Zoya</firstname>
<lastname>Mansoori</lastname>
<nickname>Sonam</nickname>
<salary>30000</salary>
</employee>
</class>
Employee.xsl
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/">
<html>
<body>
<h2>Employee</h2>
<table border = "1">
<tr bgcolor = "pink">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Salary</th>
</tr>
<xsl:for-each select = "class/employee[(@id = 001) or ((@id =
003))]">
<tr>
<td><xsl:value-of select = "@id"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "salary"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Operator Description
+ Addition operation
- Subtraction operation
* Multiplication operation
div Division operation
mod Modulo operation
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
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?>
<class>
<employee id = "001">
<firstname>Abhiram</firstname>
<lastname>Kushwaha</lastname>
<nickname>Manoj</nickname>
<salary>15000</salary>
</employee>
<employee id = "002">
<firstname>Akash</firstname>
<lastname>Singh</lastname>
<nickname>Bunty</nickname>
<salary>25000</salary>
</employee>
<employee id = "003">
<firstname>Brijesh</firstname>
<lastname>Kaushik</lastname>
<nickname>Ballu</nickname>
<salary>20000</salary>
</employee>
<employee id = "004">
<firstname>Zoya</firstname>
<lastname>Mansoori</lastname>
<nickname>Sonam</nickname>
<salary>30000</salary>
</employee>
</class>
Employee.xsl
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/">
<html>
<body>
<h2>Employee</h2>
<table border = "1">
<tr bgcolor = "pink">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Salary</th>
<th>Grade</th>
</tr>
<xsl:for-each select = "class/employee">
<tr>
<td><xsl:value-of select = "@id"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "salary"/></td>
<td>
<xsl:choose>
<xsl:when test = "salary div 25000 > 1">
High
</xsl:when>
<xsl:when test = "salary div 20000 > 1">
Medium
</xsl:when>
<xsl:otherwise>
Low
</xsl:otherwise>
</xsl:choose>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
String Functions
Here are various string functions that help you carry out XPath expression tasks:
● starts-with(string1, string2): Returns true when the first string starts with the second
string
● contains(string1, string2): Returns true when the first string contains the second string
● substring(string, offset, length?): You get a section of the string as a result. The
section starts at offset up to the length provided.
● substring-before(string1, string2): This function returns the part of string1 up before
the first occurrence of string2.
● substring-after(string1, string2): It returns the part of string1 after the first occurrence
of string2.
● string-length(string): This function returns the length of string in terms of characters.
● normalize-space(string): You can trim the leading and trailing space from string with
this function.
● translate(string1, string2, string3): It returns string1 after any matching characters in
string2 have been replaced by the characters in string3.
● concat(string1, string2, ...): You can combine all the strings using this function.
● format-number(number1, string1, string2): It returns a formatted version of number1
after applying string1 as a format string. String2 is an optional locale string.
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
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?>
<class>
<employee id = "001">
<firstname>Abhiram</firstname>
<lastname>Kushwaha</lastname>
<nickname>Manoj</nickname>
<salary>15000</salary>
</employee>
<employee id = "002">
<firstname>Akash</firstname>
<lastname>Singh</lastname>
<nickname>Bunty</nickname>
<salary>25000</salary>
</employee>
<employee id = "003">
<firstname>Brijesh</firstname>
<lastname>Kaushik</lastname>
<nickname>Ballu</nickname>
<salary>20000</salary>
</employee>
<employee id = "004">
<firstname>Zoya</firstname>
<lastname>Mansoori</lastname>
<nickname>Sonam</nickname>
<salary>30000</salary>
</employee>
</class>
Example.xsl
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/">
<html>
<body>
<h2>Employee</h2>
<table border = "1">
<tr bgcolor = "pink">
<th>Name</th>
<th>Length of Name</th>
</tr>
<xsl:for-each select = "class/employee">
<tr>
<td><xsl:value-of select = "concat(firstname,'
',lastname)"/></td>
<td><xsl:value-of select =
"string-length(concat(firstname,' ',lastname))"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Node Functions
The 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:
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/">
<html>
<body>
<h2>Employee</h2>
<table border = "1">
<tr bgcolor = "pink">
<th>Serial No</th>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Salary</th>
</tr>
<xsl:for-each select = "class/employee">
<tr>
<td><xsl:value-of select = "position()"/></td>
<td><xsl:value-of select = "@id"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "salary"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XPath Selectors
With 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 Selectors
Descendant 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.
Attribute Selectors
The XPath attribute selector matches elements based on the presence or value of a given
attribute.
Order Selectors
You can use order selectors in XPath to retrieve list elements.
Siblings
In 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:
Different Operators
There are other operators in XPath to locate elements:
Locators Description
//img image element
Attribute Selectors
Locators Description
//*[@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'
returns <section> if it has an <h1> descendant with @id=
//section[//h1[@id='hi']] 'hi'
XPath Methods
Here are some of the various XPath 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 Methods
Locator Explanation
Evaluates a decimal number and returns the largest integer less than
floor(number) or equal to the decimal number
round(decimal) Returns the nearest integer to the given number
Returns the sum of the numeric values of each node in a given
sum(node-set) node-set
String Methods
Locator Explanation
contains(space-stri Determines whether the first argument string contains the second
ng, planet-string) argument string and returns boolean true or false
concat(string1,
string2 [stringn]*) Concatenates two or more strings and returns the resulting string
Strips leading and trailing white-space from a string; replaces
normalize-space(st sequences of whitespace characters by a single space; returns the
ring) resulting string
starts-with(spacetr Checks whether the first string starts with the second string and returns
ack, space) 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(spa
cetrack, track) Returns the rest of a given string after a given substring
substring-before(s
pacetrack, tra) Returns the rest of a given string before a given substring
translate(string, Evaluates a string and a set of characters to translate and returns the
ghj, GHJ) translated string