Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Xpath in Selenium
3.
Xpath Syntax
4.
Types of Xpath Locaters
4.1.
Absolute XPath
4.2.
Relative XPath
5.
How to write Xpath using Functions
5.1.
Using Attributes (locators)
5.2.
Using Contains function
5.3.
Using text function
5.4.
Using logical AND and OR operators
5.5.
Using Starts-with function
6.
Writing Xpaths using Axes
6.1.
Using the child axis in Xpath
6.2.
Using the Ancestor axis in Xpath
7.
Frequently Asked Questions
7.1.
What is the XPath and operator in Selenium?
7.2.
What is XPath in Selenium IDE?
7.3.
What is an XPath locator?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Xpath in Selenium

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Selenium is a popular testing framework used for automating web applications. It supports various programming languages like JavaPythonC#, etc., to write scripts for test automation. One of the most significant advantages of Selenium is that it allows testers to interact with web elements using various locator strategies.

Xpath in Selenium

XPath is one of the powerful locator strategies used in Selenium to locate elements on a web page. For more information on selenium, visit this blog.

Xpath in Selenium

XPath is a query language that traverses an XML or HTML document and selects specific elements based on their attributes, tag names, and positions. XPath has a significant advantage over other locator strategies because it can locate elements that are nested deep within the structure of a web page.

XPath expressions are constructed using a set of rules. The result of the evaluation is a set of nodes that matches the expression. Selenium uses XPath expressions to locate elements on a web page and perform actions on them.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Xpath Syntax

The basic syntax of Xpath in Selenium is as follows:

XPath = //tagname[@Attribute=”Value”]


Let’s break down the syntax and understand it.

  • // denotes the current node.
  • Tagname denotes the tag name of the current node.
  • @ is to select an attribute.
  • The attribute is the selected attribute.
  • Value is the value of the selected attribute.

Types of Xpath Locaters

For example, consider the following HTML document:

<!DOCTYPE html>
<html>

<head>
	<title>XYZ Company Input Form</title>
</head>

<body>
	<div>
		<h1>XYZ Company</h1>
		<p>Welcome to XYZ Company! We specialize in providing high-quality products and services to our customers.</p>
	</div>
	<hr>
	<h2>Input Form</h2>
	<form>
		<label for="name">Name:</label>
		<input type="text" id="name" name="name"><br>


		<label for="email">Email:</label>
		<input type="email" id="email" name="email"><br>


		<label for="phone">Phone:</label>
		<input type="tel" id="phone" name="phone"><br>


		<label for="message">Message:</label><br>
		<textarea id="message" name="message"></textarea><br>


		<input type="submit" value="Submit">
	</form>
</body>

</html>


There are two types of Xpath in Selenium:

Absolute XPath

An absolute XPath expression starts with a single slash (/) and describes the exact location of an element in the document. It can fail if the structure of the document changes.

Let’s discuss the syntax of an absolute path.
 

Syntax

Xpath: /html/body/div/h1


Output

output for absolute path

Explanation

The above command selects the li elements from the first div element inside the body tag in HTML. The single slash signifies that address starts from the root of the document.

Relative XPath

A relative XPath expression starts with a double slash (//) and describes the location of an element relative to its parent element.

Let’s discuss the syntax of a relative path.
 

Syntax

Xpath: //*[@id=”name”]


Output

Output for relative path

Explanation

The above command selects all the tags whose id is name.

How to write Xpath using Functions

Xpath in Selenium provides some Xpath functions to locate Xpaths efficiently. We have discussed some important functions with examples. 

For example, Consider the following HTML document:

<!DOCTYPE html>
<html>

<head>
	<title>Example XPath</title>
</head>

<body>
	<h1>Example XPath</h1>
	<p class="description">Welcome to ninja store.</p>
	<ul>
		<li class="list">Item 1</li>
		<li class="item">Item 2</li>
		<li class="item">Item 3</li>
	</ul>
</body>

</html>

Using Attributes (locators)

We can simply use attributes or locators like, class, id, name, CSS path, href, input, etc., to select the specific elements in the document uniquely, using the below Xpath.

Syntax

XPath = //tagname[@Attribute=’Value’]


For example, To select elements whose class name is ‘item’, we can use the below Xpath

XPath = //li[@class=”item”]


Output

using attribute

Using Contains function

We can use contains() to select the elements of the given attribute having a specific value, using the below Xpath. It is used when some part of the value of attribute changes dynamically, so we can locate the element using the constant value.

Syntax

XPath = //tagname[contains(@Attribute, “Value”)]


For example, To select li elements whose class name is ‘item’, we can use the below Xpath:

//li[contains(@class,”item”)]


Output

Using contains

Using text function

We can select the tags using a substring which is a part of the selected tag. The substring or text can be the label. The Xpath is given below.

Syntax

XPath = //tag_name[contains(text(), ’Text of the element’)]


For example, To select li elements that contain the text “Item”, we can use the following XPath:

XPath = //li[contains(text(), 'Item')]


Output

using text

Using logical AND and OR operators

We can check more than one condition in a single Xpath using logical operators like AND and OR. The Xpath is given below.

OR

The syntax for using the OR operator is:

Syntax

XPath=//tagname[@attribute1=value1 or @attribute2=value1]


For example, To select li elements whose class name is ‘item’ or the text() of li element contains the substring "Item", we can use the below Xpath:

XPath = //li[contains(text(), 'Item') or contains(@class, 'item')]


Output

using or

AND

The syntax for using the AND operator is:

Syntax

XPath=//tagname[@attribute1=value1 and @attribute2=value1]


For example, To select li elements whose class name is ‘item’ and the text() of each li element contains the substring "Item", we can use the below Xpath:

XPath = //li[contains(text(), 'Item') and contains(@class, 'item')]


Output

using and

Using Starts-with function

We can use starts-with() to select those elements whose attribute’s text starts with the given value. The Xpath is given below.

XPath = //tagname[starts-with(@attribute, value)]


For example, to select elements with tag li and its given attribute starts with “item”, we can use the following XPath:

XPath = //li[starts-with(@class,'item') 


Output

Using start-with

Writing Xpaths using Axes

In XPath, the axis refers to the relationship between the current node and other nodes in the HTML/XML document. Several axes are available in XPath, including child, parent, ancestor, following-sibling, and preceding-sibling, among others. 

Using the child axis in Xpath

Using the below Xpath, we can select all the children of the ul element.

Syntax

XPath = //ul/*


Output

Using child axis

Using the Ancestor axis in Xpath

Select all the ancestor elements of the first list item having class “list”.

Syntax

XPath = //li[@class='list'][1]/ancestor::*


Output

Using ancestor

Frequently Asked Questions

What is the XPath and operator in Selenium?

In Selenium, the "and" operator in XPath is denoted by "and" or "&&," allowing you to combine conditions for more precise element identification.

What is XPath in Selenium IDE?

In Selenium IDE, XPath is used to locate elements in web pages. It helps identify elements for automated testing within the Selenium Integrated Development Environment.

What is an XPath locator?

An XPath locator is a string representation of the path to an HTML element within an XML or HTML document. It's used in Selenium for element identification.

Conclusion

In this article, we discussed Xpath in Selenium and its use cases. We also saw different functions for creating Xpath and their syntax with the help of examples. The best possible locators in Xpath depend on the specific webpage being tested. In most cases, ID is considered the best locator. It is also advised to use relative paths as they are less likely to break if the structure of the web page changes. 

Read our other related articles:

You may refer to our Guided Path on Code Studios to enhance your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Previous article
CSS Selector in Selenium
Next article
First Test Cases using Selenium
Live masterclass