Grab Deal : Flat 30% off on live classes + 2 free self-paced courses! - SCHEDULE CALL

- Selenium Blogs -

What is Xpath in Selenium? How to Write Xpath Selenium?

In Selenium automation, when web elements are not found by simple locators like class, ID, or name, etc. then XPath is just the right choice to locate web elements most easily. In this blog, we will learn about XPath basics, types of XPath, and different XPath expressions to find complex when an operation is changed, so they should be managed through XPath in Selenium.

Topics to be covered in the blog:

Let us start a quick discussion with basics first.

What is XPath in Selenium?

XPath or XML Path is a language to query XML documents. It is an important strategy for locating elements in Selenium. It is made up of a path expression associated with certain conditions. It is easy to write an XPath query to locate elements on a web page. It allows navigation through XML documents to select individual elements, attributes, or a part of the document as required. It produces reliable locators to get the things done properly. Moving ahead, let us see how to write an XPath for an XML document.

Every XML document has a tree-like structure. Here is given an XML document where you can see different tags and attributes. The document starts with the parent tag “Bookstore” that can also be considered as an element or node.


<bookstore>
<book category="cooking">
<title lang="en">Everyday Chinese</title>
<author>K.S.Bose</author>
<book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J.K.Rowling</author>
<book>

Further, “bookstore” node has a child node “book” that is further followed by an attribute “Category” whose value is given “cooking.” The “book” node further has two child nodes “tile” and “author.” Let us visualize the XML document as a tree-like structure.

Xpath in Selenium

Here, you have to start with the root node and reach the desired node as required. Once it is located, you have to pick the node with an author tag. So, XPath can be written here as:

bookstore/book[@category='children']/author

This is an XPath query for locating the author of a book whose category is children. The same technique can be used for another node whose category is cooking.

The Basic Syntax of XPath

It is easy to understand any concept with the help of a clear example. Here we took the example of a bookstore. So, what is the basic syntax of XPath? Let us learn in depth what is the syntax and how to write it.

Xpath in Selenium

  • // - double slash is used to select the current node.
  • Tag name: it is the name of the tag for a particular node.
  • @ - It is used to select attributes.
  • Attribute: it is the name of the attribute of a node.
  • Value: it is the value given to an attribute.

Common Locators that are used to find elements on a web page can be given as:

XPath Locators They are used to find different elements on a web page
ID They are used to locate elements through ID.
Name They are used to find web elements through the name of an element.
Class Name They are used to find web elements by class name.
XPath They are used to locate complex or dynamic elements on a web page that change frequently.
Link Text They are used to find elements through the text of the link
CSS Path CSS path is used to elements having no name, ID, or Class.

In the next section, we will discuss different types of XPath in Selenium with examples.

Types of XPath in Selenium

1). Absolute XPath:

It is the direct method for locating web elements, but there is one disadvantage that if the path of the web element changes, then absolute XPath will not work. For example:

/html/body/div[1]/section/div[1]/div

The biggest advantage of absolute XPath is that it starts from the single slash ‘/’ and selects an element from the root node onwards.

2). Relative XPath:

In the case of relative XPath, the path starts from the middle of the HTML DOM structure. It begins with a double slash and able to search web element from anywhere. For example:

//input[@id='ap_email']

Read: What is Actions Class in Selenium and How to use it?

Relative XPath is more common as compared to absolute XPath.

XPath Functions you should know

Selenium automation is certainly an amazing technology that offers multiple ways to identify an object or element on a web page. There are cases we face problem in identifying objects or elements having the same attributes. Here it is tough guiding Selenium how to go ahead. It is where the role of XPath functions comes in to rescue. Although the list is pretty long, and we focus on frequently used functions. These are:

  1. Basic XPath ()
  2. Contains ()
  3. Starts-with ()
  4. Text ()
  5. Using OR & AND ()

Let us learn how can we use contains () function in the XPath query.

Basic XPath:

This function selects nodes on the basis of ID, class name, name, etc. from the XML document ad given below:

xpath=//input[@name='uid']

Xpath in Selenium

Contains ():

Contain method is used within an XPath expression. If the value of an attribute frequently changes, the role of contains function comes in.  For example, login information for different users will change frequently. This method can be used for locating web elements with the available partial text. In most cases, only a certain part of the attribute is static and rets dynamic, so the concept of partial XPath works amazingly here.

Moving ahead, we will discuss a few more XPath functions.

Starts-with ()

It is used to find a web element where the value of an attribute changes on Refresh button only. It can also be used to find dynamic operation on the web page. Here, we match the starting text of an attribute to locate an element that changes frequently. For example, ID on a web page changes frequently but rest remains the same.

Text ()

It is used with the text function to locate the element with the same text. Here, we will try finding an element with the text “USER ID”. The XPath Query, in this case, will be:

xpath=//td[text()='UserID']

Xpath in Selenium

Using OR & AND Methods

In the case of the OR Expression, two conditions are used, either first or second needs to be true. It is possible that both conditions are true sometimes. Keep in mind that one condition should be true in any case to find a particular web element. In the case of the AND expression, two conditions are used, and both need to be true to locate a web element. If anyone condition fails, then it is not possible locating the desired web element.

XPATH AXES Methods

XPath axes are used to find different nodes in an XML document based on the current context node. XPath axes are used to find dynamic elements that are not possible with basic XPath having no ID, name, and the class name, etc.

AXES methods are used to locate elements that change dynamically on the refresh of an operation. A few basic Axes methods that are commonly used in a Selenium WebDriver can be given as parent, child, sibling, ancestor, self, or preceding, etc. let us explore a few common axes methods that are used frequently.

A). Following:

It is used to select all elements in the current node. USER ID is the current node here, and the basic XPath query for this axes method can be given as:

xpath=//*[@type='text']//following::input

Xpath in Selenium

Here are three nodes that match the axis query here, these are Password, Login, and Reset options. To focus on any particular element, you may use the following XPath.

Xpath=//*[@type='text']//following::input[1]

Here, you can put more numbers like [1], [2], [3] …. And so, on.

Read: A Brief Introduction on Why Is TestNG Framework So Famous?

B). Ancestor

This axes method is used to select all ancestor elements like grandparent, parent, and more for the current node as given in the example below.

Xpath=//*[text()='Enterprise Testing']//ancestor::div

Here, we are trying to find out the ancestor elements of the current node “Enterprise Testing.”

Xpath in Selenium

Here, a total of 13 nodes are matched, and if you want to focus on a particular element, you may use the below XPath where you can add numbers as per the requirement.

Xpath=//*[text()='enterprise testing']//ancestor::div[1]

C). Child

It selects all the child nodes of the current node as given in the example below.

Xpath=//*[@id='java_technologies']/child::li

The list can be longer. If you want to focus on particular nodes, only then add numbers in the end. For example:

Xpath=//*[@id='java_technologies']/child::li[1]

D). Preceding

It selects all nodes that come earlier to the current node. Let us understand the concept with the help of a simple example. What will be the XPath of you have to identify all the elements before the Login button? It can be given as:

Xpath=//*[@type='submit']//preceding::input

Xpath in Selenium

Here are two nodes matching the query; these are User ID and Password. To focus on any particular node, you may use the following syntax:

Xpath=//*[@type='submit']//preceding::input[1]

Here, you can put more numbers like [1], [2], [3] …. And so, on.

E). Following-sibling

Siblings are at the same level as the current node as given below. It helps in finding elements after the current node. For example:

Xpath=//*[@type='submit']//following-sibling::input

Xpath in Selenium

Read: How to Perform Selenium Commands on Complex WebElements?

There are only node matches for the given axis query.

F). Parent Axis Node

It finds the parent node of the current node as given in the screen below.

Xpath=//*[@id='rt-feature']//parent::div

To focus on any particular node, you may use the following syntax:

Xpath=//*[@id='rt-feature']//parent::div[1]

Here, you can put more numbers like [1], [2], [3] …. And so, on.

G). Self

It indicates the current node itself. The axis query, in this case, can be given as:

Xpath=//*[@type='password']//self::input

It is already limited to selected nodes only so you don’t have to make any modifications further.

H). Descendant:

It selects the descendants of the current node that means down under the node. The XPath query for this axis method can be given as:

Xpath=//*[@id='rt-feature']//descendant::a

The list may be longer here. To focus on any particular node, you may use the following syntax:

Xpath=//*[@id='rt-feature']//descendant::a[1]

Here, you can put more numbers like [1], [2], [3] …. And so, on according the requirement.

Final Words:

In this blog for “XPath in Selenium,” we have discussed everything about XPath from basic to advanced topics. I hope you must have a depth idea of concept now and its significance. There are more XPath functions and axis methods, but we focused on popular ones here.

To know more about XPath and how to use it with your project, join the Selenium certification course at JanBask Training, and start a successful career in automation testing right away. Selenium testing tool is used almost everywhere today, and someone skilled in Selenium will definitely get wider job options with top MNCs worldwide.



fbicons FaceBook twitterTwitter google+Google+ lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

0 day 27 Apr 2024

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

-1 day 26 Apr 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

-1 day 26 Apr 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

0 day 27 Apr 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

-1 day 26 Apr 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

-1 day 26 Apr 2024

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

7 days 04 May 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

-1 day 26 Apr 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

7 days 04 May 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

0 day 27 Apr 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

34 days 31 May 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

-1 day 26 Apr 2024

Search Posts

Reset

Receive Latest Materials and Offers on Selenium Course

Interviews