Skip to main content

You are here

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();
driver.get("http://london.craigslist.co.uk/");  // a slow loading website is good for this text. craigslist is not slow though :)
WebDriverWait wait = new WebDriverWait(driver, 5);    // define waiting period
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='jjj']/h4/a")));   // ensure the element is available for click. Check for the defined 5 seconds
element.click();

Enjoy!

Category: 

Language: 

0
No votes yet

Add new comment

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.

Disclaimer

Note that the codes and ideas expressed on this site are the authors personal views. The content of this website are the personal notes based on the learning experience of the author. The author will not be responsible for any error or damages resulting from you using the content of this website.

Premium Drupal Themes by Adaptivethemes