The implicit wait in Selenium 2 might not work for Ajax elements. We recommend you to use any one of the following workaround to handle Ajax elements.
One approach is to use FluentWait and a Predicate available with Selenium2. The advantage of this approach is that element polling mechanism is configurable. The code example below waits for 1 second and polls for a textarea every 100 milliseconds.
FluentWait fluentWait = new FluentWait(By.tagName("TEXTAREA"));
fluentWait.pollingEvery(100, TimeUnit.MILLISECONDS);
fluentWait.withTimeout(1000, TimeUnit.MILLISECONDS);
fluentWait.until(new Predicate() {
public boolean apply(By by) {
try {
return browser.findElement(by).isDisplayed();
} catch (NoSuchElementException ex) {
return false;
}
}
});
browser.findElement(By.tagName("TEXTAREA")).sendKeys("text to enter");
Another approach is to use ExpectedCondition and WebDriverWait strategy. The code below waits for 20 seconds or till the element is available, whichever is the earliest.
public ExpectedCondition visibilityOfElementLocated(final By by) {
return new ExpectedCondition() {
public WebElement apply(WebDriver driver) {
WebElement element = driver.findElement(by);
return element.isDisplayed() ? element : null;
}
};
}
public void performSomeAction() {
..
..
Wait wait = new WebDriverWait(driver, 20);
WebElement element = wait.until(visibilityOfElementLocated(By.tagName("a")));
..
}
my particular adjustment of fluentWait in the way I use is in code:
public WebElement fluentWait(final By locator, WebDriver driver) {
Wait wait = new FluentWait(driver)
.withTimeout(30, TimeUnit.SECONDS)
// .pollingEvery(5, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
// .ignoring(NoSuchElementException.class);
.ignoring(org.openqa.selenium.NoSuchElementException.class);
WebElement foo = wait.until(
new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo;
}
And the call will look like:
WebElement abracadabra = fluentWait(By.cssSelector('.elemSelector'));
For hanling alerts and getting to know whether they are shown or not, I would recommend smth like:
public boolean isAlertPresent(WebDriver driver) {
boolean presentFlag;
try {
// Check the presence of alert
Alert alert = driver.switchTo().alert();
// Alert present; set the flag
presentFlag = true;
// if present consume the alert
// alert.accept();
} catch (NoAlertPresentException ex) {
// Alert not present
// ex.printStackTrace();
presentFlag = false;
}
return presentFlag;
}
Hope this helps you.