Implicit Wait:-
Implicit waits are used when we need to wait for a certain element to appear or visible on the screen before we can proceed to next action.Once an Implicit wait is set it is set for life time of the web driver.
ImplicitWaitDemo.java
package com.example;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class ImplicitWaitDemo {
@Test
public void implicitWaitDemo () throws InterruptedException{
WebDriver driver=new FirefoxDriver();
//Print the current time
System.out.println(Calendar.getInstance().getTime());
//Implicitily wait for 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.learn-selenium.net/");
//print current time
System.out.println(Calendar.getInstance().getTime());
// Maximize the Browser Window.
driver.manage().window().maximize();
//Close the browser
driver.close();
}
}
Explicit Wait:-
Explicit waits are used when we need to wait for a certain condition to happen like a button click or an alert open.This is like waiting for a condition to happen this can be acheived using webdriver wait.Below is a simple example .
ExplicitWaitDemo.java
package com.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
public class ExplicitWaitDemo {
@Test
public void explicitWaitDeom() throws InterruptedException{
WebDriver driver=new FirefoxDriver();
driver.get("http://www.learn-selenium.net/");
//Explicitily wait for 10 seconds
WebElement myelement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/nav/div/div[1]/a[2]")));
System.out.println(myelement.getText().toString());
// Maximize the Browser Window.
driver.manage().window().maximize();
//Close the browser
driver.close();
}
}
Note/Warning: Do not use explicit and implicit wait together as the results would be unpredictable.Suppose you use implicit wait of 10 seconds and then explicit wait of 20 seconds you may get an exception any time after 10 Seconds.