What is XPath?
XPath, a crucial locator in automation testing, is used to locate web elements during script execution in the Application Under Test (AUT).ย
Most popular open-source functional automation tools depend entirely on the element’s locators to locate or correctly identify the web element while executing the automation script in a specific programming language.ย
Among the many locators available, XPath is one of the most versatile and widely used options for automation tools like Selenium and Appium.
XPath as a Locator
XPath is one of the several types of locators in Selenium used to navigate through elements and attributes in an XML document. XPath is also known as an XML path. A browser’s dev tools allow us to locate any element in an AUTย (Application Under Test).ย ย
Utilizing the findElement method in Selenium allows for precise identification of single web elements, essential for effective automation.
Proficiency in Java for Selenium testers is essential, especially when constructing complex XPath expressions for element identification.
How do you capture the XPath to find any Web Element in AUTย (Application Under Test)?
We can directly copy the XPath from the Web Browser’s Developers tool by following the below steps.ย
1. Open any web browser; let’s consider Chrome browser.ย
2. Launch the application under test.ย ย
Example: https://www.thetesttribe.com/
3. The home page contains several web elements, including “Know More,” highlighted in the above screenshot.
4. To capture the XPath, right-click on the Same elementย > Click on inspect.
5. You’ll see a highlighted line of code for the same element as in the above screenshot.
6. Right-click on the highlighted text, hover your mouse on the ‘copy’ option, and click ‘copy XPath.’
7. To validate the XPath, use Ctrl+F and paste the path you copied to double-check.
Copied path:
/html/body/div[4]/div[2]/div/div[2]/div/div/a/span/span
As we can see, only one element is available with the same XPath, with the above screenshot showing 1 of 1.
Note: It is not a good practice to copy the XPath and use it directly in the automation script. One must learn to write a customized XPath to handle dynamic web elements.
XPath Highlights
- The absolute path for the specific web element can be tracked from the root tag in the DOM.ย
- Different syntaxes and semantics can effectively locate dynamic web elements. We can also write our own customized XPath.
- Relative locators are introduced to get more flexibility while identifying complex elements.ย ย
- XPath supports backward traversal.
Example
Let’s look at a sample code for using XPath in a Selenium-Java setup to identify the element Username/Email on the login page of the https://www.thetesttribe.com/ application and enter the Username.
Prerequisites :
- Eclipse or any other compatible code editor.
- JDK
- Seleniumย 4 WebDriverย jars or dependencies.ย
Steps:
- Create a Java class; for example, in the sample code below, the class name is Find_salaryReport.
Inside the primary method, keep the below code.
//WebDriver instance using Browser driver
WebDriver wd = new FirefoxDriver();
//Launch the Application using the get method
wd.get("https://www.thetesttribe.com/my-account/edit-account/");
//Store the XPath in a string variable, i.e. KnowMore
String KnowMore= "//*[@id=\"username\"]";
//Create a webElement. Locate the element using //findElement method
WebElement el_KnowMore = wd.findElement(By.xpath(KnowMore));
//send the test data using the sendKeys method
el_KnowMore.sendKeys("g123aya45tri");
Notes:ย
- WebDriver is an interface.ย
- findElement is a method to identify a single Web Element at a time.
- sendKeys: sendKeys is used to send the test data to a specific entity at execution.ย For example, we provided the test data for email and password at the time of execution.ย
- Familiarize yourself with the types of XPath in Selenium to improve element selection strategies
Types of XPath
A. Relative XPathย
B. Absolute XPathย
Relative XPath
โ Relative XPath starts with //.ย
โ Relative XPath will directly identify the element in DOM through the element’s attribute and value specified in it or text associated with it.ย
โ One can handle dynamic elements using customized relative XPath.ย
โ Relative XPath is faster than absolute XPath.ย
Syntaxes we can follow to construct the relative XPath :ย
A. XPath with attribute and valueย
//tagName[@AttributeName=โvalueโ]ย
Exampleย
//input[@id=โ123"]
//name[@name=โunmโ]
B. XPath with contains and text
Syntax:ย
//tagName[contains(text( ),โtextvalโ)]ย
Example:ย
//span[contains(text( ),โRegister hereโ)]ย
C. XPath indexing
(//TagName[@attribute=โvalueโ])[1]ย
(//TagName[@attribute=โvalueโ])[2]ย
(//TagName[@attribute=โvalueโ])[3]
Note : here, tagName can be input , img , a, span , div , table … as per the elements tagName in DOM.ย
We can use the dev tools to get the proper attribute and value of the element in the DOM and test the customized XPath.ย
Note: We can use other strategies to handle the dynamic elements using relative paths.
Absolute XPath
- Absolute XPath starts with /ย
- Absolute XPath searches the element in the DOM from the root tag, i.e.,/html/body/…
Example :
/html/body/form/input
/html/body/div/div[2]/input
Note: It is tedious to write the absolute XPath as it will take more time to track the sequential tags correctly from the root tag to the element’s tag.
Absolute XPath will always search from the root tag of the DOM.
You may sometimes come across Stale Element Reference Exception which we covered in one of our previous posts.
How can we use an index in XPath?
When we are getting similar types of elements in a page to identify, like two radio buttons are there and we need to select one, in DOM, also we are getting the same attributes and values for both radio buttons; here, we need to use the index to identify them uniquely.
Enclose the XPath in ( ) and forward by index in [ ]ย
Let’s consider that the registration page for any subscription registration form has two radio buttons that can be tested by clicking “yes” or “no.”
We need to identify both.ย
So here, we can use an index.
Syntax:ย
(//tagName[@common-attribute="value"])[1]ย
XPath:ย
(//input[@type="radio"])[1] -> Yesย
(//input[@type="radio"])[2] -> No
Scenario: To identify Yes or No on this registration page below.
XPath for identifying Yes:
(//input[@type=โradioโ])[1]
XPath for identifying No:
(//input[@type=โradioโ])[2]
Advanced XPath Strategies
- Contains method in XPath:ย
Syntaxย
//TagName[@attribute1=โvalue1โ or @attribute2=โvalue2โ] //TagName[@attribute1=โvalue1โ and @attribute2=โvalue2โ]
Using the Contains method, identify the Book a Free Demo button on the OrangeHRM home page.ย
(//button[contains(text(),โBook aโ)])[1]ย
Starts With Methodย ย
Syntax: //TagName[starts-with(@attrbute,โtext valueโ)]
Using and, or in XPathย
Syntax :ย ย
//TagName[@attribute1=โvalue1โ or @attribute2=โvalue2โ] //TagName[@attribute1=โvalue1โ and @attribute2=โvalue2โ]ย
XPath by textย
//TagNam[text()=โtext valueโ]ย
Other strategies, such as Ancestor, Following, Child, and Preceding, can effectively replace the Relative Locator concept from Selenium 4 onwards.ย ย
Mastering how to create XPath in Selenium is crucial for precise element targeting.
RelativeLocator is a concrete class that provides many methods, likeย ย
above()ย
below()ย
toLeftOf()ย
toRightOf()ย
near()ย
Examples of Relative locators:ย
// To identify a specific element with a given XPath above the element having id 12.ย
RelativeLocator.with(By.xpath("")).above(By.id("12"));ย
// To identify a specific element with a given id below the element having a given XPath.
RelativeLocator.with(By.id("")).below(By.xpath(""));
Resources
- Check the Selenium Documentation.
- The courses on Thrive Edschool cover these topics in detail:
- Selenium with Python Tutorial for Beginners