Using XPath in Selenium to Finding an Element (Simple Steps)

Using Xpath in Selenium-Java Setup to Find an Element

Using XPath in Selenium in Application Under Test

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/

An example of Know More button on The Test Tribe Homepage

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.

Know more button for xpath in Inspect element

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
Screenshot 2025 01 25 160943

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.

Screenshot 2025 01 25 161201

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");
Screenshot 2025 01 25 162327
logging in on www.thetesttribe.com/login

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

Gayatri Mishra - author of the blog

Written by

Gayatri Mishra is a seasoned Corporate SDET Freelance Coach with over 15 years of experience in providing software testing training, specializing in web automation training for freshers and offering personalized one-on-one sessions.

Leave a Reply

Your email address will not be published.

Related Posts

Check Thrive EdSchool

Advertisement (Know More)

Get Top Community News

    Top Event and other The Test Tribe updates to your Inbox.

     

    Categories

    Tags

    [sibwp_form id=2]
    The Test Tribe Logo
    Privacy Overview

    This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.