XPath Selenium tactics will help you to write effective selenium find by statements especially for locating dynamic web elements in selenium webdriver projects. Generally, test automation engineers struggle to write dynamic XPath at the beginning of their test automation journeys. To address this pain, I prepared this tutorial for writing effective XPath in Selenium.
I shared all my tactics such as XPath contains text, sibling, ancestor, child, preceding, descendant, parent, and so on. I hope this article will help you to write smart and non-brittle selenium find by statements in your projects. Let’s start!
In our test automation codes, we generally prefer to use id, name, class, etc. these kinds of locators. However, sometimes we could not find any of them in the DOM and also sometimes locators of some elements change dynamically in the DOM. In these kinds of situations, we need to use smart locators. These locators must be capable to locate complex and dynamically changing web elements. In below sections, I will share with you 15 tactics to write effective XPath locators.
We can find the location of any element on a web page using XML path expressions. The basic syntax for XPath is shown below:
Syntax = //tagname[@attribute=’Value‘]
Example = //input[@id=’user-message‘]
Absolute and Relative XPath
- It is a direct way to locate an element.
- It is very brittle.
- Starts with single slash “/” that means starting to search from the root.
- Starts from the middle of the HTML DOM.
- Starts with a double slash “//” that means it can start to search anywhere in the DOM structure.
- Shorter than Absolute XPath.
- Less fragile.
Example: //*[@class=’panel-body’]//li[contains(text(),’entered in input field’)]
Example: //input[@id, ‘user-message’]