This section will show a solution to handle ajax while perform selenium scripts with java.
selenium have methods to check status of web element such as: isDisplayed(), isVisibled(), isSelected() but in actual, we face many cases that theirs functions is not work well.
For wait function, Selenium have 3 types:
- implicit wait (not recommend)
- explicit wait (recommend)
- fluent wait (recommend but need more programming skill to handle it)
For handle that, we need methods to check/verify page loading/ajax to make the automation scripts more stabled. Below some functions I created when i worked on projects before.
-
wait for element
public WebElement waitForElement(WebDriver driver, WebElement el) { WebElement element = (new WebDriverWait(driver,10)).until(ExpectedConditions.elementToBeClickable(el)); return element; }
2. wait for page loaded
;
3. wait element with timeout
public void waittimeElement(WebElement element, int seconds) throws Exception { long endtime = System.currentTimeMillis() + seconds * 1000; while (System.currentTimeMillis() < endtime) { if (element.isDisplayed()) { break; } } }