![]() |
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.
Syntax:
Use cases of XPath include:
Steps for Locating Elements using XPath and JavaStep 1: Create a ProjectCreate 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 ConfigurationConfigure 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 DependencyInclude the Selenium dependency in your project’s pom.xml file by adding the following code:
Ensure that your pom.xml file reflects the updated dependencies as shown above: ![]() Step 4: Building the Main ClassCreate the main class for your automation. Develop a script that performs the following tasks:
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.
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 AutomationValidate 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:ConclusionIn 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. |
Reffered: https://www.geeksforgeeks.org
Selenium |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |