How to verify a Text present in the loaded page through WebDriver


I need to verify a Text present in the page through WebDriver. I like to see the result as boolean (true or false). Can any one help on this by giving the WebDriver code?

This question is tagged with webdriver selenium-webdriver assertion

~ Asked on 2012-11-05 06:25:29

The Best Answer is


As zmorris points driver.getPageSource().contains("input"); is not the proper solution because it searches in all the html, not only the texts on it. I suggest to check this question: how can I check if some text exist or not in the page? and the recomended way explained by Slanec:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));

~ Answered on 2014-06-18 14:53:54


Yes, you can do that which returns boolean. The following java code in WebDriver with TestNG or JUnit can do:

protected boolean isTextPresent(String text){
        boolean b = driver.getPageSource().contains(text);
        return b;
    catch(Exception e){
        return false;

Now call the above method as below:

assertTrue(isTextPresent("Your text"));

Or, there is another way. I think, this is the better way:

private StringBuffer verificationErrors = new StringBuffer();
try {
                  assertTrue(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*    Your text here\r\n\r\n[\\s\\S]*$"));
  } catch (Error e) {

~ Answered on 2013-01-31 07:32:44

Most Viewed Questions: