如果 Selenium2 在有限时间轮询后无法检索 WebElement 对象,我有这个想法,即故障转移到 JavascriptExecutor。如您所见,该方法具有在调用 getElementByLocator 时需要预先定义“故障转移”Javascript 片段的限制。我想不出任何方法来动态地做到这一点。如果有人可以帮助我改进这一点,我将奖励最佳建议的答案,无论它多么小。
// failover example1: "document.getElementById('gbqfb')"
// failover example2: "document.querySelector("div#gbqfb")"
public static WebElement getElementByLocator(final By locator, String failover) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS);
.ignoring(NoSuchElementException.class,StaleElementReferenceException.class);
WebElement we = wait.until( ExpectedConditions
.presenceOfElementLocated( locator ) );
if ( we.isNull() ) {
JavascriptExecutor js = (JavascriptExecutor) driver;
if ( !failover.isEmpty() ) {
we = (WebElement)js.executeScript( failover );
if ( we.isNull() ) LOG.info("Still couldn't get element.");
} else {
LOG.info("No failover String available. Cannot try with " +
"a JavascriptExecutor.");
}
}
return we;
}