Monday, January 28, 2013

WebDriver: isTextPresent

WebDriver is way far better in many ways than selenium RC, However if you have migrated from Selenium RC, you will miss few functions. And two on the top lists are isTextPresent and isElementPresent. Though it's not available in webdriver, it's not complicated to implement, there are various ways to the same thing. I will discuss few ways in following post.

  1. Using in in-build PageSource API
  2. public boolean isTextPresent(String text){
     if (driver.getPageSource().contains(text)) {
      return true;
     }
     else 
      return false;
    }
    Disadvantages:
    • It is too slow as compared other two options as it checks in whole page source.
    • Result might be wrong as it doesn't verify only visible text on webpage but whole source code (script + html tags)
  3. Using XPath
  4. public boolean isTextPresent(String text){
     try {
      driver.findElement(By.xpath("//*[contains(.,'"+text+"')]"));
      return true;
     }catch(NoSuchElementException e){
      return false;
     }
    }
    Disadvantages:
    As it is using XPath, it might be slow on IE than on Firefox and Chrome Browsers.
  1. Using Selenium RC Function.
  2. public boolean isTextPresent(String text){
     try{
      WebDriverBackedSelenium selenium = new WebDriverBackedSelenium(driver, "");
      if(selenium.isTextPresent(text)){
       return true;
      }else{
       return false;
      }
     }catch(Exception e){
      return false;
     }
    }
    Disadvantages:
    It is using Selenium RC code.