如何让Selenium 2.0等待页面加载?
当前回答
使用这个函数
public void waitForPageLoad(ChromeDriver d){
String s="";
while(!s.equals("complete")){
s=(String) d.executeScript("return document.readyState");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
其他回答
在python中,你可以简单地使用:
driver.implicitly_wait(30)
使用下面的代码,它是非常容易和简单的页面加载。
public void PageLoad(IWebDriver driver, By by)
{
try
{
Console.WriteLine("PageLoad" + by);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(by));
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); // 30 seconds wait until element not found.
wait.Until(ExpectedConditions.ElementToBeClickable(by));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Assert.Fail("Element not found!")
}
}
我希望这对你有所帮助。
在脚本中调用下面的函数,这将等待页面未使用javascript加载
public static boolean isloadComplete(WebDriver driver)
{
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
|| ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
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
对于隐式等待,你可以使用如下代码:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)
为了使网页等待一个特定的对象是可见的或某些条件是真实的。您可以使用网页驱动程序等羽。
//120 is maximum number of seconds to wait.
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable("CONDITITON"));
在Java中,另一种选择是让线程在特定的时间内休眠。
Thread.sleep(numberOfSeconds*1000);
//This line will cause thread to sleep for seconds as variable
我创建了一个方法来简化线程。睡眠的方法
public static void wait_time(int seconds){
try {
Thread.sleep(seconds*1000);
}catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
使用wait_time(10)方法;线程将休眠10秒。
推荐文章
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 如何在POM.xml中引用环境变量?
- 如何在android中复制一个文件?
- 将整数转换为字符串,以逗号表示千
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- 如何在清洁模式下运行eclipse ?如果我们这样做会发生什么?
- 获取java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory异常
- Java中的正则表达式命名组
- c#和Java的主要区别是什么?
- 什么是NullPointerException,我如何修复它?
- 在Java中使用“final”修饰符
- 无法在Flutter上找到捆绑的Java版本
- 如何在Kotlin解析JSON ?
- 如何在新的材质主题中改变背面箭头的颜色?