tom tom - 2 months ago 8
Java Question

WebDriver - wait for element using Java

I needed something similar to waitForElementPresent to check whether element is displayed before I click it. I thought the implicitWait should cover this. So I used the following:

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


and then click by

driver.findElement(By.id(prop.getProperty(vName))).click();


Unfortunately sometimes it waits for the element and sometimes not. I looked for a while and found this solution :

for (int second = 0;; second++) {
Thread.sleep(sleepTime);
if (second >= 10)
fail("timeout : " + vName);
try {
if (driver.findElement(By.id(prop.getProperty(vName)))
.isDisplayed())
break;
} catch (Exception e) {
writeToExcel("data.xls", e.toString(),
parameters.currentTestRow, 46);
}
}
driver.findElement(By.id(prop.getProperty(vName))).click();


And it waited all right, but before timing out it had to wait 10 times 5, 50 seconds. A bit much. So I set the implicitly wait to 1sec and all seemed fine until now. Because now some things wait 10s before timeout but some other things time out after 1s.

How do you cover the waiting for element present/visible in your code? Any hint is appreciable.

Answer

This is how I do it in my code.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

or

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

to be precise.

See also: