0
0
Selenium Javatesting~5 mins

XPath with text() in Selenium Java

Choose your learning style9 modes available
Introduction

XPath with text() helps find elements by matching their visible text. It makes locating elements easier when you know the exact text shown on the page.

You want to click a button with a specific label like 'Submit'.
You need to verify that a message with exact text appears on the page.
You want to find a link by its visible text to navigate somewhere.
You want to check if a warning or error message with certain text is displayed.
Syntax
Selenium Java
//tagname[text()='exact text']

Replace tagname with the HTML element name like button or a.

The text inside text()='...' must match exactly, including spaces and case.

Examples
Selects a button element whose visible text is exactly 'Submit'.
Selenium Java
//button[text()='Submit']
Selects a link (a) with the text 'Home'.
Selenium Java
//a[text()='Home']
Selects a div element with the exact text 'Welcome to our site!'.
Selenium Java
//div[text()='Welcome to our site!']
Sample Program

This test opens a webpage, finds a button with the exact text 'Submit' using XPath with text(), and prints if it is visible.

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 XPathTextExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/testpage");

            // Find button with text 'Submit'
            WebElement submitButton = driver.findElement(By.xpath("//button[text()='Submit']"));

            // Check if button is displayed
            if (submitButton.isDisplayed()) {
                System.out.println("Submit button found and visible.");
            } else {
                System.out.println("Submit button not visible.");
            }

        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Text matching with text() is exact. Extra spaces or different case will cause no match.

Use contains(text(), 'partial text') if you want to match part of the text.

Always prefer unique text to avoid selecting multiple elements accidentally.

Summary

XPath with text() helps find elements by their visible text.

It requires exact text match unless using contains().

Useful for buttons, links, messages, and labels with known text.