Best practice to wait for a change with Selenium Webdriver?

You can use implicit WebDriver wait :

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

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.

More here: http://seleniumhq.org/docs/04_webdriver_advanced.html#implicit-waits


I suggest use org.openqa.selenium.support.ui.ExpectedConditions.attributeToBe(WebElement element, String attribute, String value).

e.g.

WebDriverWait wait = new WebDriverWait(driver, 5); // time out after 5 seconds
someElement.click();
wait.until(ExpectedConditions.attributeToBe(someElement, "sort-attribute", "ascending"));

(docs)


It's a recurring problem of Selenium. I am not sure about a "best" implementation existing. I believe it's largely depending on the situation.

Concerning AJAX-driven changes, I would generally use a waitForElementPresent or a waitForElementNotPresent depending on the changes the AJAX call will make on the page.


I feel that using the WebDriverWait is pretty useful. One change you can make in your code is use -

webelement.isDisplayed(); 

instead of getting the style attribute.