如何让Selenium 2.0等待页面加载?
当前回答
Ruby实现:
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until {
@driver.execute_script("return document.readyState;") == "complete"
}
其他回答
使用类WebDriverWait
也可以看这里
您可以期望显示一些元素。类似于c#:
WebDriver _driver = new WebDriver();
WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 1, 0));
_wait.Until(d => d.FindElement(By.Id("Id_Your_UIElement")));
如果你想等待一个特定的元素加载,你可以在RenderedWebElement上使用isdisplay()方法:
// Sleep until the div we want is visible or 5 seconds is over
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
// Browsers which render content (such as Firefox and IE) return "RenderedWebElements"
RenderedWebElement resultsDiv = (RenderedWebElement) driver.findElement(By.className("gac_m"));
// If results have been returned, the results are displayed in a drop down.
if (resultsDiv.isDisplayed()) {
break;
}
}
(例子来自《5分钟入门指南》)
对于使用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);
使用下面的代码,它是非常容易和简单的页面加载。
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!")
}
}
我希望这对你有所帮助。
NodeJS答案:
在Nodejs中,你可以通过承诺得到它…
如果您编写了这段代码,您可以确保当您到达then…
driver.get('www.sidanmor.com').then(()=> {
// here the page is fully loaded!!!
// do your stuff...
}).catch(console.log.bind(console));
如果您编写了这段代码,您将进行导航,selenium将等待3秒……
driver.get('www.sidanmor.com');
driver.sleep(3000);
// you can't be sure that the page is fully loaded!!!
// do your stuff... hope it will be OK...
来自Selenium Documentation (Nodejs):
这一点。get(url)→Thenable<undefined> 调度命令导航到给定的URL。 返回一个承诺,该承诺将在文档完成加载时得到解决。
推荐文章
- 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不是主类在其清单文件