☰ See All Chapters |
Explicit Wait in Selenium WebDriver
Selenium WebDriver provides the “WebDriverWait” and “ExpectedCondition” classes for implementing an explicit wait condition. The following example sets the explicit wait time for a new WebElement called “loginWindow” that is identified by its xpath ("//*[@id=\"ui-id-1\"]") to 15 seconds. This overrides implicit timeout for this WebElement.
WebDriverWait wait = new WebDriverWait(driver, 15); WebElement loginWindow; loginWindow= wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"ui-id-1\"]"))); loginWindow.click(); |
Below are the some common conditions that you frequently use while automating application:
Condition | WebDriver ExpectedConditions |
An element is visible and enabled | elementToBeClickable(By locator) |
An element is selected | elementToBeSelected(WebElement element) |
Presence of an element | presenceOfElementLocated(By locator) |
Specific text present in an element | textToBePresentInElement(By locator, java.lang.String text) |
Element value | textToBePresentInElementValue(By locator, java.lang.String text) |
Title | titleContains(java.lang.String title) |
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait;
public class Example { public static void main(String[] args) { // configure chromedriver System.setProperty("webdriver.chrome.driver", "F:\\My_Programs\\Selenium\\ChromeDriver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, 20);
// Launch website driver.get("https://www.registration.tools4testing.com/");
// Click on the Login Button driver.findElement(By.id("loginopener")).click(); // Focus on the dialog window by click on dialog window title WebElement loginWindow; loginWindow= wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"ui-id-1\"]"))); loginWindow.click();
// Enter user name driver.findElement(By.id("loginUsername")).sendKeys("manu.m@tools4testing.com");
// Enter user password driver.findElement(By.id("loginPassword")).sendKeys("hello");
// Click on the Login Button driver.findElement(By.id("loginButton")).click();
WebElement loginSuccessWindow; loginSuccessWindow = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"ui-id-3\"]"))); loginSuccessWindow.click();
driver.findElement(By.xpath("//*[@id=\"loginSuccessDialog\"]/div/span/input")).click();
//close the driver driver.quit();
} } |
All Chapters