Smart ways to use XPath in Selenium – [2022 Updated]
Locators in Selenium test automation help to find the unique DOM elements. There are different types of locators CSS, ID, Class, XPath, etc. The XPath Locator is the most commonly used in test automation.
XML Path Language is popularly abbreviated as XPath, it locates the element uniquely in the DOM tree. In test automation, Locators and Selectors are used interchangeably. Now lets discuss all the smart ways to use Xpath in Selenium and before that know all about Xpath below.
Table Of Contents
- 1 Basic Xpath Syntax
- 2 How to Construct XPath Using Chrome Browser DevTools Window?
- 3 Types of Xpath
- 4 How to Create Dynamic XPath in Selenium?
- 5 How to Write XPath for Different Types of HTML Tags and Attributes?
- 6 How to Write XPath Contains() Function in Selenium Web Driver?
- 7 Using Contains() in Xpath for Class Attribute
- 8 XPath Matching Text Elements
- 9 How to Match Exact Text in XPath?
- 10 Partial Match of Text Content in Xpath
- 11 Using Conditions in XPath
- 12 Starts-With in Xpath
- 13 XPath Axes
- 14 How to Write Codeless Automation Scripts Using Testsigma
Basic Xpath Syntax
// : Stands current node
tag_name : HTML tag name example input, div, span etc.
@attribute: Name of the attribute class, id, aria-label etc.
value: value of the attribute
How to Construct XPath Using Chrome Browser DevTools Window?
Xpath can be constructed using any modern browser. As Chrome is the most used browser, the demonstration is given in Chrome. Steps remain mostly the same for other browsers as well.
1. Open the web page.
2. Use Shortcut CTRL+SHIFT+I for Windows Or CMD+SHIFT+C for Mac.
3. The Developer window with the active Elements tab opens up.
4. Click on Element Selector, and select the Element.
5. Copy Xpath
Right Click on the DOM Tree-specific element Click on Copy then Click on Copy Xpath
6. Verify Xpath, In the Elements Tab open search using CTRL + F (Windows) or CMD + F (Mac), and paste the copied Xpath, if the Xpath is correct, the element should highlight.
Chrome uses its way to construct the Xpath, sometimes the copied Xpath will be long, So it is not recommended to use the Copy Xpath, This way of copying Xpath is helpful for beginners until they are comfortable with constructing one on their own. In this article, you learn the best way to construct the XPath with XPath Locator strategies and keywords.
Types of Xpath
Xpath can be broadly classified into
1. Absolute Xpath
2. Relative Xpath
What is Absolute Xpath?
The absolute Xpath is often referred to as Full Xpath, which starts from the beginning of the HTML document (root). The absolute with Xpath starts with a single slash (/).
Example of Absolute Xpath
Why Absolute Xpath is Not Recommended for Selenium Test Automation?
Absolute XPath is not recommended for any test automation the reason is the absolute XPath starts from the root of the DOM Structure/Tree document. If there are any elements added as a child in between the path due to application improvement or feature delivery your test automation code breaks. So in test automation typically the relative Xpath locator is the best way to use it.
What is Relative Xpath?
Unlike Absolute Xpath, the relative XPath starts from the middle of the DOM Tree and it starts with double slashes (//). Since the Relative Xpath contains less top-level HTML Element node dependency it is more stable and typically used in test automation.
Example of Relative Xpath
How to Create Dynamic XPath in Selenium?
XPath provides many keywords and methods which help to write XPath for any complicated scenarios, Some times you may not be able to construct Selectors using CSS selectors but you can achieve it through XPath.
As mentioned above the typical Xpath Syntax in Selenium as follows
How to Write XPath for Different Types of HTML Tags and Attributes?
XPath can be written for any type of element such as img, div, span, a, input, etc attributes such as id, class, value, href, src. In simple any HTML tag or any HTML attribute that is rendered as part of the DOM tree is eligible for Xpath.
style=”padding-top: 10px”>Below are some Basic Examples of XPath with different attributes and tag name
XPath for id attribute
XPath for button element class value
XPath for Image with src attribute
As shown above you can construct XPath for the Combination of Tagname and attribute value.
How to Write XPath Contains() Function in Selenium Web Driver?
Contains() method in Selenium XPath is typically used when the value of an Element or attribute changes dynamically. Lets know how to use Contains() for Xpath in Selenium.
Using Contains() in Xpath for Class Attribute
Consider an example, you have HTML code like below
<button type=”button” class=”getting started mbg blueocean”>getting started</button>
In the above code, the class name is getting started mbg blueocean, and the mbg word is dynamic and it changes each time you load the page, the static text is getting started so you need to use contains for the class attribute you can use it like below.
XPath Contains Functions for Attributes.
The above example demonstrates the usage of contains for class, Just like the class you can use any attribute inside the contains.
Note: instead of tag name you can use star (*) which matches all the tags.
Example Usage of Contains() for Xpath in Selenium for Different Attributes
XPath contains a function for the id attribute
XPath contains a function for the name attribute
XPath contains function for href attribute
XPath contains function for image src attribute
XPath contains function for name attribute
XPath contains a function for the type attribute
XPath Matching Text Elements
The XPath provides a text() function for manipulation of text in Xpath, using the text() function you can match the Exact text or Partial text in XPath.
How to Match Exact Text in XPath?
Sometimes, there will not be any unique attributes for some HTML tags, only the text attached to that element is unique. In such cases, you choose to use text() in XPath.
Take an example of the Invitation page
There is no unique attribute available, however, there is a text Continue which is unique.
Syntax for Matching Exact Text in Xpath Selenium
For the above scenario, you can write Xpath to match the exact text below
Partial Match of Text Content in Xpath
Let’s have a profile page where there is a greeting message, like ” Hi David! Welcome to Testsigma”, here only David the Firstname changes from one account to another the Welcome to Testsigma is static for all users. So when you locate the element you need to match the text only welcome to Testsigma part.
Syntax for Partial Matching Text in XPath
Based on the above syntax for the given scenario, you can write the XPath like below
//p[contains(text(),’Welcome to testsigma’)]
Using Conditions in XPath
XPath allows you to use the conditions such as AND, and OR. Sometimes you might want either of the attribute value should be present for example you have HTML code
<input name=”q” type=”text” title=”Search”>
OR Condition in Xpath
You might want to match either the name attribute or title attribute should match, in that case, you can use OR
//input[@title=’Search’ or @name=’q’]
The above Xpath expression matches either title or name if anyone is true then it matches that DOM element.
First, it searches for an input element with attribute title=’Search’ if it finds true then returns that element, if it doesn’t find any then it goes to the next condition which is @name=’q’ if it finds any element then returns the corresponding element if there is no match for the second element then returns no element. In short, any one or both of the conditions should be true.
AND Condition in XPath
If you require to match both conditions, then you need to use AND.
Considering the example above, if you want to match both title and name, instead of or you can put and like below
//input[@title=’Search’ and @name=’q’]
First, it matches the title if there is no element found (if it is false) then it returns no matching element found, if the first condition is true then evaluate the second condition if it is false then returns no matching element if it is true then it returns the corresponding element. In short, Both conditions should be true.
Consider an example where the value changes dynamically, but the first part of the id is always constant like in the below image.
Starts-With in Xpath
In the above use case, you can use the starts-with functionality of XPath
XPath Starts-with Syntax:
Using the syntax you can construct xpath for the above scenario
i. The XPath 2.0 onwards both starts-with and ends-with are supported.
ii. The Xpath ends-with can be used the same way as starts-with, the ends-with useful if the initial value changes and the end value remains constant
iii. Example of ends with //input[ends-with(@id,’end-value’)]
XPath Axes are helps to identify the elements with relationships such as a parent, child, sibling, etc. XPath Axes refer to the axis on which elements are lying relative to an element
List of XPath Axes methods
Xpath Following Axis
Selects everything in the DOM Tree after the closing tag of the current node
Xpath Ancestor Axis
The Ancestor Axis Matches all the ancestors (parent, grandparent, etc.) of the current node.
Child Axis in Xpath
The Child Axis in Xpath matches all the children of the current node
Preceding Axis in Xpath
Matches all nodes that appear before the current node in the HTML Document, except ancestors, attributes, and namespace
Following-sibling Axis in Xpath
The Following sibling selects all siblings in HTML Document after the current node
Parent Axis in Xpath
Selects the parent of the current node in HTML Documents
Self Axis in Xpath
The Self Axis is rarely used in writing Xpath, this is used for selecting the current node
Descendant Axis in Xpath
Selects all descendants including children, grandchildren, etc. of the current node in HTML Document
Preceding Sibling Axis in Xpath
The preceding sibling used for selecting the all siblings before the current node
Descendant-Or-Self Axis in Xpath
The descendant-or-self is used for selecting all descendants including children, grandchildren, etc. of the current node and the current node itself.
Ancestor-or-self Axis in XPath
Ancestor or self is used to identify the context node and the ancestor element from the context node.
Attribute Axis in Xpath
The attribute axis in Xpath selects all attributes of the current node
//input[attribute::name = ‘btnK’]
1. Whenever there is more than one match you can always use an index like    etc. This selects 1st 2nd and 3rd elements respectively.
2. / and //are most used in Xpath, you can use / and // at the start or in the middle
3. / matches root node, if you double slash (//) is used in the middle of any tag, it defines a descendant relationship
4. Xpath is recommended to use when there is no other way of selecting an element. For example, if the id is available then the id takes priority over the XPath
5. A single dot (.) is used to select the current node
6. A double dot (..) is used to select the parent. For example, if you want to get the parent of the body tag you can simply use //body/.
The Automation framework or test script requires coding knowledge, most of the time beginners find difficulties in understating the automation framework and working on the test script. Testsigma provides codeless automation. You do not need a single line of code. Testsigma also has a dedicated chrome recorder plugin, you can simply install it on google chrome and start automating.
How to Write Codeless Automation Scripts Using Testsigma
1. Download and install the Testsigma Recorder plugin for Chrome
2. Login to Testsigma with Credentials ( If you don’t have an account create one)
3. Create a New Project by providing the Project Name
4. Click on Create new Testcase
5. Enter the Testcase Name and Base URL
6. Click on record Test
7. A New Browser window opens up and recording starts
8. Perform a set of actions as per your test case, once done click on finish
9. You will be landed on Testsigma Project Dashboard and all the recorded steps will be shown.
10. Click on Start to Run the Testsigma Automated Testcases
11. You will be asked for Configurations, Choose the configuration from the drop-down list
12. Click on Run now, Wait until it finishes
13. If the test fails, you can even edit selectors