如何让Selenium 2.0等待页面加载?
当前回答
在Webdriver/Selenium 2软件测试工具中有两种类型的等待。一种是隐式等待,另一种是显式等待。两者(隐式等待和显式等待)在WebDriver中都很有用。使用等待,我们告诉WebDriver在进入下一步之前等待一定的时间。可以使用隐式等待来等待页面加载。
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
其他回答
Imran对Java 7的回答是:
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wdriver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState"
).equals("complete");
}
});
如何让Selenium在单击后等待页面加载提供了以下有趣的方法:
存储旧页面中对WebElement的引用。 点击链接。 继续调用WebElement上的操作,直到抛出StaleElementReferenceException。
示例代码:
WebElement link = ...;
link.click();
new WebDriverWait(webDriver, timeout).until((org.openqa.selenium.WebDriver input) ->
{
try
{
link.isDisplayed();
return false;
}
catch (StaleElementReferenceException unused)
{
return true;
}
});
对于使用java 8向前的程序员,可以使用下面的代码来使用显式等待等待页面加载。
JavascriptExecutor js = (JavascriptExecutor) driver;
new WebDriverWait(driver, 10).until(webDriver ->
(js).executeScript("return document.readyState;").equals("complete"));
注意:在我上面的代码中使用Lambda表达式,它只在java 8的后续版本中可用。
对于使用低版本Java(即Java 8以下)的程序员,可以使用:
ExpectedCondition<Boolean> cond = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver input) {
JavascriptExecutor js = (JavascriptExecutor) driver;
return js.executeScript("return document.readyState;").equals("complete");
}
};
new WebDriverWait(driver, 100).until(cond);
The best way to wait for page loads when using the Java bindings for WebDriver is to use the Page Object design pattern with PageFactory. This allows you to utilize the AjaxElementLocatorFactory which to put it simply acts as a global wait for all of your elements. It has limitations on elements such as drop-boxes or complex javascript transitions but it will drastically reduce the amount of code needed and speed up test times. A good example can be found in this blogpost. Basic understanding of Core Java is assumed.
http://startingwithseleniumwebdriver.blogspot.ro/2015/02/wait-in-page-factory.html
隐式和显式的等待更好。
但是如果你在Java中处理一个异常,那么你可以使用这个来等待页面重新加载:
Thead.sleep(1000);
推荐文章
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象
- 在Java中保存最后N个元素的大小有限的队列
- 如何运行一个类从Jar不是主类在其清单文件