我的脚本有问题。我正在使用 Selenium WebDriver 来驱动网页,但我经常收到 ElementNotFound 异常。该页面需要一两秒才能加载。
我的代码如下:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
try
{
WebElement username = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class='gwt-TextBox']")));
username.sendKeys(usernameParm);
}
catch (Exception e) {
e.printStackTrace();
}
大约一秒后,异常仍然会抛出。然后,如果我通过运行以下命令来测试它:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
try
{
WebElement username = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class='gwt-TextBox1']")));
username.sendKeys(usernameParm);
}
catch (Exception e) {
e.printStackTrace();
}
知道 TexBox1 不存在,然后它会抛出相同的异常。看来是不等了。在第二个实例中,我希望它超时,并且不会抛出 ElementNotFoundException。
我的实现可能是错误的。
最佳答案
查看我关于此主题的帖子:https://iamalittletester.wordpress.com/2016/05/11/selenium-how-to-wait-for-an-element-to-be-displayed-not-displayed/ 。那里有代码片段。基本上我的建议是不要使用 FluentWait,而是:
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
ExpectedCondition elementIsDisplayed = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver arg0) {
try {
webElement.isDisplayed();
return true;
}
catch (NoSuchElementException e ) {
return false;
}
catch (StaleElementReferenceException f) {
return false;
}
}
};
wait.until(elementIsDisplayed);
使用您认为合适的任何超时值来定义 TIMEOUT(我相信您在最初的问题中说过 10 秒)。
关于java - Selenium WebDriver FluentWait,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41615876/