Thursday, May 24, 2012

Again good practice to look-up ajax element in Selenium 2 / WebDriver

Here is small and good-working example on how to lookup "unstable elements" on your web page.
.
 public WebElement lookupXPathExists(final String xpath) throws YourOwnAutomationException{
  WebElement handledElement;
  try{
   handledElement = new WebDriverWait(getDriver(), AWAITING_THRESHOLD_MS/1000, 1000).until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
     logger.debug("Attempt to find: " + xpath);
     return d.findElement(By.xpath(xpath));
    }});;
  }catch(TimeoutException e){
   throw new YourOwnAutomationException("Lookup for element ["
     + xpath + "]" + " failed after "
     + AWAITING_THRESHOLD_MS + " ms awaiting.");
  }
  return handledElement;
 }

 public WebElement lookupXPathExistsRelative(final WebElement base, final String xpath) throws YourOwnAutomationException{
  WebElement handledElement;
  try{
   handledElement = new WebDriverWait(getDriver(), AWAITING_THRESHOLD_MS/1000, 1000).until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
     logger.debug("Attempt to find: " + xpath);
     return base.findElement(By.xpath(xpath));
    }});;
  }catch(TimeoutException e){
   throw new YourOwnAutomationException("Lookup for element ["
     + xpath + "]" + " failed after "
     + AWAITING_THRESHOLD_MS + " ms awaiting.");
  }
  return handledElement;
 }

First method looks up the element within the entire page. The second one shows how to lookup ajax element within another web element.
getDriver() returns your current instance of WebDriver.
AWAITING_THRESHOLD_MS/1000 - just the number of seconds to wait while the attempts are taken. I use such the weird representation just not to break my old constants :)