Verify Text Attribute in Selenium

Profile picture for user arilio666

Using the getPageSource() method, we can verify whether a text is present on the page. In selenium getPageSource() works by fetching the whole page source, which verifies the text. The method returns contents in texts, which is very helpful.

Example:

In this example, let us try to verify the first text, "Cypress Testing Tool."


{
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://www.programsbuzz.com/course/cypress-tutorial");
        driver.manage().window().maximize();
        String t = "Cypress Testing Tool";
        // WebElement textt =
        // driver.findElement(By.xpath("//a[normalize-space()='Cypress Testing
        // Tool']"));
        if (driver.getPageSource().contains("Cypress Testing Tool")) {
            System.out.println("Text: " + t + " is present. ");
        } else {
            System.out.println("Text: " + t + " is not present. ");
        }
    }
}
  • We first stored the required text in a variable.
  • Then, we verified whether the text exists on the page or not using the getPageSource() method inside the if statement with the help of contains.
  • It seems it exists, and this is how we can verify texts in selenium using java.