We use findElement with XPath to locate a specific element on a web page when other simpler locators are not enough.
findElement by xpath in 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.
WebElement loginButton = driver.findElement(By.xpath("//button[@id='login']"));WebElement firstLink = driver.findElement(By.xpath("//a[text()='Home']"));WebElement inputField = driver.findElement(By.xpath("//input[@type='text' and @name='username']"));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.
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(); } } }
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.
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.