0
0
Selenium Javatesting~5 mins

findElement by xpath in Selenium Java

Choose your learning style9 modes available
Introduction

We use findElement with XPath to locate a specific element on a web page when other simpler locators are not enough.

When you want to find a button or link that has no unique ID or class.
When you need to locate an element based on its text content.
When the element's position relative to other elements matters.
When CSS selectors cannot express the needed path to the element.
When testing dynamic web pages where element attributes change.
Syntax
Selenium Java
WebElement element = driver.findElement(By.xpath("xpath_expression"));

The xpath_expression is a string that describes the path to the element.

This method returns the first matching element or throws an exception if none found.

Examples
Finds a button element with the ID 'login'.
Selenium Java
WebElement loginButton = driver.findElement(By.xpath("//button[@id='login']"));
Finds the first link with the exact text 'Home'.
Selenium Java
WebElement firstLink = driver.findElement(By.xpath("//a[text()='Home']"));
Finds an input field of type text with the name 'username'.
Selenium Java
WebElement inputField = driver.findElement(By.xpath("//input[@type='text' and @name='username']"));
Sample Program

This test script opens a login page, finds username and password input fields and the login button using XPath, fills in credentials, clicks the button, and prints a success message.

Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FindElementByXPathExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/login");
            WebElement usernameInput = driver.findElement(By.xpath("//input[@name='username']"));
            usernameInput.sendKeys("testuser");
            WebElement passwordInput = driver.findElement(By.xpath("//input[@name='password']"));
            passwordInput.sendKeys("password123");
            WebElement loginButton = driver.findElement(By.xpath("//button[text()='Login']"));
            loginButton.click();
            System.out.println("Login button clicked successfully.");
        } catch (Exception e) {
            System.out.println("Element not found or error occurred: " + e.getMessage());
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Always use clear and stable XPath expressions to avoid flaky tests.

If findElement does not find the element, it throws NoSuchElementException.

Use browser DevTools to test XPath expressions before using them in code.

Summary

findElement by xpath helps locate web elements when simple locators are not enough.

XPath expressions can find elements by attributes, text, or position.

Always handle exceptions to keep tests stable.