Wednesday, July 1, 2015

SELENIUM : WAITING FOR CONDITIONS TO BE AVAILABLE


While testing a very slow loading website, the dreaded "NoSuchElementException" exception can occur even though the element does exist on the page. The problem can be that the code is running faster than the site loads. The "ExpectedCondition" class ensures that the program waits for a designated period of time before throwing the "NoSuchElementException" error message.


In the code below, we navigate to craigslist, take 5 seconds to wait for the required element to appear and be ready for clicking. Then click the element.

WebDriver driver = new FirefoxDriver();

// a slow loading website is good for this text. craigslist is not slow though :)

driver.get("http://london.craigslist.co.uk/");  

// define timeout for waiting period

WebDriverWait wait = new WebDriverWait(driver, 5);    

// ensures the element is available for click. Check for the defined 5 seconds before timeout

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='jjj']/h4/a")));   

element.click();

No comments:

Post a Comment