Friday, December 19, 2014

How to check if the text is present or not in Webpage Using Selenium Webdriver

TEXT

There could be two ways to achieve this. 

Way 1: Using gettext() method .

Way 2: Get the page source using getPageSource() method then verify. 

Demo: 
  1. Navigating to google.com 
  1. Identifying the button using ID property 
  1. Getting the button text using gettext() methiod 
  1. Comparing the expected and actual text using if-else 


Source Code :

package verifytest; 
import java.util.concurrent.TimeUnit; 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 
 public class verifytestpresent { 
    public static void main(String[] args) { 
        WebDriver driver = new FirefoxDriver(); 
        driver.get("http://www.google.com"); 
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
        //verify 'Google search' text from Search button in the web page or not using gettext() 
        String expectedtext = "Google Search";  
        //first way to verify by using locator and getText() method 
        String actualText = driver.findElement(By.id("gbqfba")).getText(); 
        if(actualText.contains(expectedtext)){ 
            System.out.println("1) Expected text '"+expectedtext+"' present in the web page found using gettext()."); 
        }else{ 
            System.out.println("1) Expected text '"+expectedtext+"' is not present in the web page found using gettext()."); 
        } 
        //Way 2 : Get the page source using getPageSource() method then verify.  
        String pageSource = driver.getPageSource(); 
        if(pageSource.contains(expectedtext)){ 
        System.out.println("2) Expected text '"+expectedtext+"' present in the web page found using getpageSource()."); 
        }else{ 
        System.out.println("2) Expected text '"+expectedtext+"' is not present in the web page found using getpageSource()."); 
        } 
    } 
} 

Hope you like this post
Hit a like on facebook..
Thankyou..



No comments:

Post a Comment