isDisplayed() 在我看来不是很好的方法。从等待中获得一些想法:显式和隐式等待机制:
Explicit wait
WebDriverWait.until(condition-that-finds-the-element)
Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit Waits:
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});
Implicit Waits:
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
The example what you have given both do exact same thing..
In Explicit wait, WebDriver evaluates the condition every 500
milliseconds by default ..if it is true, it comes out of loop
Where as in ImplicitWait WebDriver polls the DOM every 500
milliseconds to see if element is present..
Difference is
1. Obvious - Implicit wait time is applied to all elements in your
script but Explicit only for particular element
2. In Explicit you can configure, how frequently (instead of 500
millisecond) you want to check condition.
3. In Explicit you can also configure to ignore other exceptions than
"NoSuchElement" till timeout..
你可以在这里获得更多信息
我还使用流利的等待机制来等待元素在页面上呈现。实际上,您将 css 选择器或 xpath 传递给函数并简单地获取 web 元素。
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo; } ;
流利的等待说明
希望这现在清楚了)