Selenium

Selenium Expected Condition Example

Photo of Sarad DhungelSarad DhungelDecember 27th, 2016Last Updated: April 9th, 2019
0 236 3 minutes read

In this example set, I will be covering how the Selenium Excepted Conditions works. Before diving into use ofExpectedConditions in Selenium we must understand why do we need it.

By default, Selenium doesn’t wait for elements once the page gets loaded. Thus, if the element is not present, then Selenium will throwNoSuchElement Exception. To overcome this, we need to implement concepts of wait in Selenium.

If you are new to Selenium and wants to learn what isSelenium WebDriver, you can refer to my previousexamples.
 
 
 

1. Introduction

Wait:

By implementing the wait, we can lapse the execution of automated procedure. There are two possible ways to do so:

  1. Implicit Wait: This wait will make all the automated procedure to wait specified time. No matter if the element is found within that time or not, this wait will be executed throughout the life of execution of scripts.
  2.  Explicit Wait:  Unlike Implicit wait, this type of wait can be applied to desired scripts by setting certain conditions for them. There are two types of explicit wait. Static explicit wait makes the execution to stop for given time even if the elements has been identified eg:thread.sleep() whereas dynamic or smart explicit wait, we can choose many of available conditions for each scripts to wait required time. By default, expected condition will check for elements every 500 ms to verify the condition. If the condition is true within 500 ms then it will proceed to another scripts without waiting the given time limit.ExpectedConditions class extends java.lang.Object. It has several methods available. We will be covering methods likeelements to be clickable, which is most common methods widely used to navigate to the link.
    For more available methods you can click here.

ImplicitWait.java

package com.javacodegeeks.Selenium.ExpectedConditions;import java.io.File;import java.io.IOException;import java.util.concurrent.TimeUnit;import org.apache.commons.io.FileUtils;import org.openqa.selenium.By;import org.openqa.selenium.OutputType;import org.openqa.selenium.TakesScreenshot;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.remote.Augmenter;public class ImplicitWait {public static void main(String [] args) throws InterruptedException{String exePath = "/Users/saraddhungel/Downloads/chromedriver";System.setProperty("webdriver.chrome.driver", exePath);WebDriver driver = new ChromeDriver();driver.get("http://www.google.com/");implicitWait(driver);    WebElement hello = driver.findElement(By.xpath("//input[@id='lst-ib']"));    hello.sendKeys("Java Code Geeks");    hello.submit();        WebElement hello1 = driver.findElement(By.partialLinkText("Java Code Geeks"));    hello1.click();   WebDriver Driver = new Augmenter().augment(driver);File srcFile = ((TakesScreenshot)Driver).getScreenshotAs(OutputType.FILE);try{FileUtils.copyFile(srcFile, new File("//Users//saraddhungel//dsesktop//image.png"));}catch(IOException e){System.out.println(e.getMessage());}}public static void implicitWait(WebDriver driver){driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);}}

The implicit wait throughout the execution WebDriver instance. It will make each and every methods wait for given 10 seconds. Since the page gets loaded andJava Code Geeks page gets searched within 10 second, it will take screenshot of after 10 second and the file is saved on desktop as image.png

However, if within given time, elements are not found then it will throw NosuchElementException.
Note: Implicit wait might be able to find some elements in DOM which are present yet are not visible within given time. This is not recommended wait if there are over 100s of scripts that needs to be run since it will slow the execution.

Want to master Selenium?
Subscribe to our newsletter and download theSeleniumProgramming Cookbookright now!
In order to get you prepared for your Selenium development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

ExplicitWait.java

package com.javacodegeeks.Selenium.ExpectedConditions;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.openqa.selenium.By;import org.openqa.selenium.OutputType;import org.openqa.selenium.TakesScreenshot;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.remote.Augmenter;import org.openqa.selenium.support.ui.ExpectedConditions;import org.openqa.selenium.support.ui.WebDriverWait;public class ExplicitWait {public static void main(String [] args){String exePath = "/Users/saraddhungel/Downloads/chromedriver";System.setProperty("webdriver.chrome.driver", exePath);WebDriver driver = new ChromeDriver();driver.get("http://www.google.com/");WebElement hello = driver.findElement(By.xpath("//input[@id='lst-ib']"));hello.sendKeys("Java Code Geeks");hello.submit();explicitWait(driver, "Java Code Geeks");    WebElement hello1 = driver.findElement(By.partialLinkText("Java Code Geeks"));    hello1.click();        WebDriver Driver = new Augmenter().augment(driver);File srcFile = ((TakesScreenshot)Driver).getScreenshotAs(OutputType.FILE);try{FileUtils.copyFile(srcFile, new File("//Users//saraddhungel//dsesktop//image.png"));}catch(IOException e){System.out.println(e.getMessage());}}public static void explicitWait(WebDriver driver,String text ){WebDriverWait wait = new WebDriverWait(driver, 10);WebElement hello1 = wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText(text)));}}

In this case of Explicit wait, soon when the page gets loaded, it will check for the given condition within the given time i.e it will search the link with text “Java Code Geeks”. Then as soon as it finds the linktext, the page gets loaded and screenshot is captured. By default, explicit waits check each condition within 500 ms so if within that time condition is true, it will get executed. This is the best wait method recommended for test cases with larger scripts.

2. Conclusion

This example set is a simple attempt to demonstrate importance of wait and types of waits available along with their functionality.

3. Download the Eclipse Project

This was an example of Wait in Selenium

Download
You can download the source code of this example here:Selenium ExpectedCondition

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Sarad DhungelSarad DhungelDecember 27th, 2016Last Updated: April 9th, 2019
0 236 3 minutes read
Photo of Sarad Dhungel

Sarad Dhungel

I am a graduate in Computer Engineering from Howard University. Third place award winner in Intel-Cornell Cup. Passionate about new emerging software and technology. During free time, I enjoy reading about politics, business, spirituality, technology and traveling.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.