Locating Strategies By XPath Using Java
Last Updated :
14 Mar, 2024
Web application testing must be rigorous and thorough. For this reason, many tests for web applications are automated. Selenium is an open-source framework that allows us to automate web browser testing. In the following article, we will explore how to use XPath to locate elements on our HTML code using Java and Selenium. We will further see an example of how we can manipulate these elements using the code itself.
What is XPath?
XPath (XML Path Language) is a query language and expression syntax used for navigating and selecting elements from XML (Extensible Markup Language) documents.
- It provides a way to locate and retrieve information from XML documents by specifying the path to the desired elements or nodes.
- XPath uses a compact and expressive syntax to describe the structure and relationships within an XML document.
- It operates on the logical structure of the XML document, treating it as a tree of nodes.
Syntax:
//tagname[@attribute = ‘value’]
Use cases of XPath include:
- Selecting Nodes: XPath expressions can be used to select specific nodes or sets of nodes within an XML document.
- Filtering Nodes: XPath allows you to filter nodes based on certain conditions, such as attributes or content.
- Navigation: XPath provides a way to navigate through the hierarchical structure of an XML document, moving from one node to another.
- Accessing Attributes: You can use XPath to access and retrieve values of attributes associated with elements.
- Searching for Patterns: XPath supports the use of wildcards and patterns to find nodes that match a specific structure or naming convention.
Steps for Locating Elements using XPath and Java
Step 1: Create a Project
Create a Maven project in your Java IDE, such as IntelliJ IDEA, selecting Java 17 as the language. Navigate to File > New > Project to initiate the project setup.

Step 2: Set Up the Project Configuration
Configure the project settings by providing a name and selecting Maven as the build type. Specify Java-17 as the language in the opened dialogue box after clicking the Project button in the previous step.

Step 3: Add the Selenium Dependency
Include the Selenium dependency in your project's pom.xml file by adding the following code:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.18.1</version>
</dependency>
Ensure that your pom.xml file reflects the updated dependencies as shown above:

Step 4: Building the Main Class
Create the main class for your automation. Develop a script that performs the following tasks:
- Open the browser
- Toggle to Change the default theme
- Close the Browser
Ensure your main class includes the necessary Selenium and WebDriver code to accomplish these automation steps without human interactions.
Example:
The below Java program demonstrates locating a webpage element using XPath (double slash) for a theme toggle button. It opens a Chrome browser, navigates to a specified URL, and toggles the theme by identifying the button through XPath, showcasing a simple example of an XPath-based locating strategy.
Java
// Java Program for Locating Strategies
// By XPath Using Java
// Importing Selenium Libraries
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args)
{
// Use the ChromeDriver for the pre-installed Chrome
// browser
WebDriver driver = new ChromeDriver();
// Open the browser and navigate to the specified
// URL
driver.get("https://www.geeksforgeeks.org/");
// Locate the element using XPath for the theme
// toggle button
WebElement themeToggleButton
= driver.findElement(By.xpath(
"//button[@aria-label='toggle theme']"));
// Toggle the theme by clicking the identified
// element
themeToggleButton.click();
// Close the browser
driver.quit();
}
}
Now when we run this code, we will see that your browser automatically opens, navigates to the specified URL toggles the theme, and closes on its own. It's a pretty quick process so be very attentive (that's why it's automated).
Step 5: Testing the Automation
Validate the automation by executing the code. Verify that the output demonstrates the successful completion of the automation tasks, including opening the browser, toggling the theme, and closing the browser.
Output:

Conclusion
In conclusion, XPath proves invaluable for web application testing with Selenium in Java, providing a concise syntax for precise element location and manipulation. Using XPath's navigation and filtering capabilities, the automated script efficiently opens, toggles the theme, and closes the browser, showcasing the simplicity and effectiveness of XPath-based locating strategies in Java for web automation.
Similar Reads
Automation Testing - Software Testing
Automated Testing means using special software for tasks that people usually do when checking and testing a software product. Nowadays, many software projects use automation testing from start to end, especially in agile and DevOps methods. This means the engineering team runs tests automatically wi
15+ min read
Automation Testing Roadmap: A Complete Guide to Automation Testing [2025]
Test automation has become a vital aspect of the Software Development Life Cycle (SDLC), aimed at reducing the need for manual effort in routine and repetitive tasks. Although manual testing is crucial for ensuring the quality of a software product, test automation plays a significant role as well.
10 min read
How to Start Automation Testing from Scratch?
Automation Testing is the practice of using automated tools and scripts to execute tests on software applications, reducing manual effort and increasing efficiency. Starting automation testing from scratch involves several key steps, including selecting the right automation tool, identifying test ca
8 min read
Benefits of Automation Testing
In today's fast-paced software development landscape, integrating automation into development and testing processes is crucial for staying competitive. Automation testing offers numerous benefits, including cost savings, faster feedback loops, better resource allocation, higher accuracy, increased t
4 min read
Stages of Automation Testing Life Cycle
In this article, we will explore the phases and methodologies involved in automation testing and the phases of the automation testing lifecycle. We'll cover everything from scoping your test automation to creating a solid test plan and strategy. You'll also learn about setting up the perfect test en
12 min read
Top Automation Testing Books For 2024
In this article, we can explore the top 10 books for automation testing, providing a top-level view of each book's content material and why it's worth considering for everybody interested in this sector. Table of Content Top 10 Books for Automation Testing BooksConclusionFAQs on Top Automation Test
12 min read
Top Test Automation mistakes and Tips for QA teams to avoid them
In the dynamic landscape of software testing, avoiding common test automation pitfalls is crucial for QA teams aiming for efficient and successful testing processes. This article delves into prevalent errors in test automation and provides valuable insights on how QA teams can steer clear of these m
7 min read
Essential Skills for a Successful Automation Tester
In the domain of software testing, automation plays a crucial role in ensuring efficiency, accuracy, and speed. However, to be a successful automation tester, one must possess a specific set of skills beyond just technical proficiency. This article explores the essential skills required for automati
6 min read
Steps to Select the Right Test Automation tools
Selecting the right test automation tools is critical for ensuring efficient and effective testing processes in software development projects. In this article, we will discuss the key steps involved in choosing the most suitable automation tools for your project needs. From understanding project req
5 min read
Best Test Automation Practices in 2024
Test Automation continues to evolve with new technologies and methodologies emerging each year. In 2024, staying updated with the latest best practices is crucial for efficient and effective testing processes. From robust test design to continuous integration and deployment, this article explores th
7 min read