Tomando un paso más allá respuesta de nilesh, también puede permitir búsquedas más finos-sintonizado (por ejemplo, en el contexto de un WebElement) mediante la interfaz SearchContext:
Function<SearchContext, WebElement> elementLocated(final By by) {
return new Function<SearchContext, WebElement>() {
public WebElement apply(SearchContext context) {
return context.findElement(by);
}
};
}
ejecución se lleva a cabo por una instancia de FluentWait <SearchContext> (en lugar de WebDriverWait). Dése una interfaz de programación agradable envolviendo su ejecución y el control de excepciones necesarias en un método de utilidad (la raíz de la jerarquía de tipos PageObject es un buen lugar): el uso
/**
* @return The element if found before timeout, otherwise null
*/
protected WebElement findElement(SearchContext context, By by,
long timeoutSeconds, long sleepMilliseconds) {
@SuppressWarnings("unchecked")
FluentWait<SearchContext> wait = new FluentWait<SearchContext>(context)
.withTimeout(timeoutSeconds, TimeUnit.SECONDS)
.pollingEvery(sleepMilliseconds, TimeUnit.MILLISECONDS)
.ignoring(NotFoundException.class);
WebElement element = null;
try {
element = wait.until(elementLocated(by));
}
catch (TimeoutException te) {
element = null;
}
return element;
}
/**
* overloaded with defaults for convenience
*/
protected WebElement findElement(SearchContext context, By by) {
return findElement(context, by, DEFAULT_TIMEOUT, DEFAULT_POLL_SLEEP);
}
static long DEFAULT_TIMEOUT = 3; // seconds
static long DEFAULT_POLL_SLEEP = 500; // milliseconds
Ejemplo:
WebElement div = this.findElement(driver, By.id("resultsContainer"));
if (div != null) {
asyncSubmit.click();
WebElement results = this.findElement(div, By.id("results"), 30, 500);
if (results == null) {
// handle timeout
}
}
¿Puede explicar "Función"? No existe tal objeto llamado "Función" y se preguntaba si podría ponerlo en contexto mejor? – djangofan