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?
Note: Not in boolean
WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");
if(driver.getPageSource().contains("Ur message"))
{
System.out.println("Pass");
}
else
{
System.out.println("Fail");
}
Driver.getPageSource() is a bad way to verify text present. Suppose you say, driver.getPageSource().contains("input");
That doesn't verify "input" is present on the screen, only that "input" is present in the html, like an input tag.
I usually verify text on an element by using xpath:
boolean textFound = false;
try {
driver.findElement(By.xpath("//*[contains(text(),'someText')]"));
textFound = true;
} catch (Exception e) {
textFound = false;
}
If you want an exact text match, just remove the contains function:
driver.findElement(By.xpath("//*[text()='someText']));
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));
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){
try{
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) {
verificationErrors.append(e.toString());
}
Below code is most suitable way to verify a text on page. You can use any one out of 8 locators as per your convenience.
String Verifytext= driver.findElement(By.tagName("body")).getText().trim(); Assert.assertEquals(Verifytext, "Paste the text here which needs to be verified");
If you are not bothered about the location of the text present, then you could use Driver.PageSource property as below:
Driver.PageSource.Contains("expected message");