Implicitly Wait in Selenium Webdriver

Now day most of application are formed using ajax statements, ajax makes the DOM elements to load at different times but selenium tries to find the element after the moment, it completes the previous line execution.

Due following reasons application element may take a while to load.

  • Poor Server Response time
  • Ajax Loading
  • Size of the page
  • Internet Speed
  • System hardware
  • Browser slowness / less responsive ness
  • Element created using javascript

Selenium Webdriver tries to find the element without bothering about whether elements are loaded or not, and selenium webdriver throws NoSuchElementException if element is not present.

Implicitly wait is one of the way to request selenium not throw any exception until provided time. Default wait time of the selenium is 500 milli-seconds, implicitly wait overrides the default wait time of the selenium webdriver.

If element is found before implicitly wait time, selenium moves to next commands in the program without waiting to complete the implicitly wait time, this wait is also called dynamic wait.

Implicit wait is set for the entire duration of your webdriver and is set at the start of your program. Most of the automation tester writes the implicit wait after creation of browser object.

Implicit wait tries to find the element in first go, if element is not present implicit wait tries to find the element after 500ms of first polling, if element is not available on second time also then implicit wait tries third time after 500 ms of second try and it goes on till the time reaches the 30 seconds

What it does is, in case while executing, if your webdriver doesn't finds any element then instead of throwing an exception, implicit wait makes your driver to wait for the specified wait time and then try to find the element once again.

If the driver still does not finds the element then it throws exception. Implicit wait does the same for all the elements in your program, so you just have to set it once.


						WebDriver driver = new ChromeDriver(); 
						// set implicit wait tme as 30 Seconds
						driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
						

Ex: Let's say that you give an Implicit wait of 30 sec, now while executing, your webdriver is not able to find an element, but since you've set implicit wait, the webdriver waits instead of throwing exception.

Lets say the time the webdriver searched for element is t=0.Now the webdriver waits for 30 sec, and at t=30.500( polling time of the implicitly wait is 500 milli-seconds) driver tries to find the element again, if it finds the element then it performs the particular action on the element and if it doesn't, it throws NoSuchElementException exception.


Complete Implicitly wait program

						public class MultiValueDropdownSelectByValue {
							public static void main(String[] args) throws Exception {
								// set the geckodriver.exe property
								System.setProperty("webdriver.gecko.driver", "C:/~/geckodriver.exe");
								// open firefox
								WebDriver driver = new FirefoxDriver();
								// set implicitly wait time for 1 Minute
								driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
								// open webpage
								driver.get("https://chercher.tech/practice/practice-dropdowns");
								// find the dropdown using xpath
								WebElement dropdownElement = driver.findElement(By.xpath("//select[@id='second']"));
								// create object for Select class
								Select dropdown = new Select(dropdownElement);
								// select options from the dropdown options which have value as 'donut', 'burger'
								dropdown.selectByValue("donut");
							}
						}
						

Handle dropdowns in selenium

Scope of Implicitly Wait in Selenium Webriver

Implicitly Wait is applicable only to findElement and findElements no other statement in selenium.

Once set, the implicit wait is set for the life of the WebDriver object instance. You can re-assign the implicit wait time anywhere you want.

When does Implicitly Wait is applicable for findElements method. :

Implicit wait in selenium is applicable for all findElement statements, but applicability of implicit wait to the findElements is Limited.

Implicitly wait is applicable on findElements only when there is no elements present, selenium webdriver moves to next command the moment it finds a single element.

If there is Zero matching elements selenium waits till the time it reaches provided implicitly wait

Scenario 1 : Consider a page having 100 checkboxes and applied implicit wait is 30 Seconds
When the page is loading selenium tries to find all the matching elements, but at there moment there no matching elements .

After 10 seconds of wait 1 check box is loaded, now selenium finds that one checkbox and concludes that there is only one element, so it ends the wait and moves to next command.

Selenium doesnot wait till 100 check boxes loaded into page, as webdriver doesnot know how many elements going to to be present on the page.

Scenario 2 : Consider a page having 0 checkboxes and applied implicit wait is 30 Seconds
Selenium tries to find all the matching elements inDOM, but so far no check box is loaded.

Now there is zero match so selenium waits till 30 seconds, and if doesnot find element after 30 seconds selenium webdriver throws NoSuchElementEXception

Supported Timeunits with Implicit Wait

Implicitly wait in selenium webdriver supports all the time unit from nano-Seconds to Days, all the units are present in the TimeUnit abstract class.

All the values (variable ) present in the TimeUnit are Constants, I guess you already got that from the UPPERCASE style itself. UPPERCASE is used to mean a value is constant

  • TimeUnit.NANOSECONDS : represents nano seconds (10pow-9 of a second is nano second)
  • TimeUnit.MICROSECONDS : represents micro seconds (10pow-6 of a second is micro second)
  • TimeUnit.MILLISECONDS : represents mill seconds (10pow-3 of a second is micro second i.e 1000 milli seconds is a second)
  • TimeUnit.SECONDS : represent a second
  • TimeUnit.MINUTES : represent minutes, a minute is 60 seconds
  • TimeUnit.HOURS : represent hour, a hour is 60 minutes
  • TimeUnit.DAYS : represents a day, a day is 24 hours
Implement ImplicitWait using sleep method in selenium

We can implement Implicitly Wait using Thread.sleep() method, by dividing the total wait time with 300ms time and we have to store that value in a variable for looping purpose, then we have make the thread to sleep for the 300ms and then re-try to find the element. Follow below steps to implement.

Explanation :Let's understand the principle of the implicitly wait, implicitlyWait waits for the element to present on webpage with given time limit, implicitly wait keeps trying to find the element till the time expires.

Steps to Implement :
1. Create a class called ImplicitWaitWithSleep.

2. Create a static method called implicitlyWithSleep and method should accept seconds as parameter.

3. Initiator the count variable for counting purpose.

4. For calculating purpose we have to convert seconds into milli-seconds, as implicit wait polls once in 300 milli-seconds.

5. Create a while loop with condition as true, this is also called as infinite loop as we donot have any condition

6. Write our finding element code inside the try block, so that we can catch exceptions if element is not there, make sure what kind of exception you want to catch ( for implicit wait we have to catch NoSuchElementException ).

8. We have to break the loop when we find the element (inside try block).

7. Verify the condition that our tries( count ) exceeded the max time limit, if it crosses throw a new NoSuchElementException exception.

8. We have make the program to sleep for 300 milli-seconds before polling again. With this end the implicitlyWithSleep method.

9. Open and navigate to google page in browser inside the main method.

10. Access the method to set the text to google search bar


						public class ImplicitWaitWithSleep {
							public static WebDriver driver;
							public static void main(String[] args) {
								// set chrome driver exe path
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								// create object for chrome browser
								 driver = new ChromeDriver();
								// navigate to google
								driver.get("https://google.com/");
								implicitlyWithSleep(30);
							}
							
							public static void implicitlyWithSleep(long timeLimit){
								System.out.println("Custom implicitly wait with selenium");
								//set the counter for terminate purpose
								long count = 0;
								// calculate the number of tries 
								long tries = (timeLimit * 1000) /300;
								while(true){
									try {
										System.out.println("Trying for : "+count+" time(s)");
										// try to find the element and send keys
										driver.findElement(By.xpath("//input[@name='q']")).sendKeys("Implicit wait with sleep");
										System.out.println("element found");
										// end the loop as we found the element 
										break;
									} catch (NoSuchElementException e) {
										if (count > tries) {
											// throw exception if element not found after exception. 
											throw new NoSuchElementException("Element not fount after : "+timeLimit+"seconds");
										}
										// sleep for 300 milli seconds,
										// try to find the element after 30 seconds of sleep
										try {
											Thread.sleep(300);
										} catch (InterruptedException e1) {
											System.out.println("Sleep interupted");
										}
									}
									count++;
								}
							}
						}
						

Learn about Parameterized Constructor in Selenium and Java

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link for the training starting from 15th Nov 2018
 
Join My Facebook Group
Join Group