如何让Selenium 2.0等待页面加载?
当前回答
对于存在的任何元素使用if条件和
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
其他回答
使用类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")));
我的方法很简单:
long timeOut = 5000;
long end = System.currentTimeMillis() + timeOut;
while (System.currentTimeMillis() < end) {
if (String.valueOf(
((JavascriptExecutor) driver)
.executeScript("return document.readyState"))
.equals("complete")) {
break;
}
}
对于隐式等待,你可以使用如下代码:
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秒。
public static int counter = 0;
public void stepGeneralWait() {
boolean breakIt = true;
while (true) {
breakIt = true;
try {
do{
// here put e.g. your spinner ID
Controller.driver.findElement(By.xpath("//*[@id='static']/div[8]/img")).click();
Thread.sleep(10000);
counter++;
if (counter > 3){
breakIt = false;
}
}
while (breakIt);
} catch (Exception e) {
if (e.getMessage().contains("element is not attached")) {
breakIt = false;
}
}
if (breakIt) {
break;
}
}
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
在python中,你可以简单地使用:
driver.implicitly_wait(30)
推荐文章
- 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不是主类在其清单文件