Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

JavaSeleniumWebdriverSelenium WebdriverSelenium Ide

Java Problem Overview


With "HTML" Selenium tests (created with Selenium IDE or manually), you can use some very handy commands like WaitForElementPresent or WaitForVisible.

<tr>
	<td>waitForElementPresent</td>
	<td>id=saveButton</td>
	<td></td>
</tr>

When coding Selenium tests in Java (Webdriver / Selenium RC—I'm not sure of the terminology here), is there something similar built-in?

For example, for checking that a dialog (that takes a while to open) is visible...

WebElement dialog = driver.findElement(By.id("reportDialog"));
assertTrue(dialog.isDisplayed());  // often fails as it isn't visible *yet*

What's the cleanest robust way to code such check?

Adding Thread.sleep() calls all over the place would be ugly and fragile, and rolling your own while loops seems pretty clumsy too...

Java Solutions


Solution 1 - Java

Implicit and Explicit Waits

Implicit Wait

> An implicit wait is to tell WebDriver to poll the DOM for a certain > amount of time when trying to find an element or elements if they are > not immediately available. The default setting is 0. Once set, the > implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

> An explicit waits is code you define to wait for a certain condition > to occur before proceeding further in the code. The worst case of this > is Thread.sleep(), which sets the condition to an exact time period to > wait. There are some convenience methods provided that help you write > code that will wait only as long as required. WebDriverWait in > combination with ExpectedCondition is one way this can be > accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

Solution 2 - Java

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));

> > This waits up to 10 seconds before throwing a TimeoutException or if > it finds the element will return it in 0 - 10 seconds. WebDriverWait > by default calls the ExpectedCondition every 500 milliseconds until it > returns successfully. A successful return is for ExpectedCondition > type is Boolean return true or not null return value for all other > ExpectedCondition types.


WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

> Element is Clickable - it is Displayed and Enabled.

From WebDriver docs: Explicit and Implicit Waits

Solution 3 - Java

Well the thing is that you probably actually don't want the test to run indefinitely. You just want to wait a longer amount of time before the library decides the element doesn't exist. In that case, the most elegant solution is to use implicit wait, which is designed for just that:

driver.manage().timeouts().implicitlyWait( ... )

Solution 4 - Java

Another way to wait for maximum of certain amount say 10 seconds of time for the element to be displayed as below:

(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.findElement(By.id("<name>")).isDisplayed();

            }
        });

Solution 5 - Java

For individual element the code below could be used:

private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
for (int second = 0;; second++) {
 			if (second >= 60){
 				fail("timeout");
 			}
 			try {
 				if (isElementPresent(By.id("someid"))){
 					break;
 				}
 				}
 			catch (Exception e) {
 				
 			}
 			Thread.sleep(1000);
 		}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonikView Question on Stackoverflow
Solution 1 - JavaPetr JanečekView Answer on Stackoverflow
Solution 2 - Javauser1710861View Answer on Stackoverflow
Solution 3 - JavaMike KwanView Answer on Stackoverflow
Solution 4 - JavaVeeksha A VView Answer on Stackoverflow
Solution 5 - JavaRipon Al WasimView Answer on Stackoverflow