如何让Selenium 2.0等待页面加载?
当前回答
Use:
driver.manage().timeOuts().implicitlyWait(10, TimeUnit.SECONDS);
这意味着对网页上元素的任何搜索都需要时间来加载。implicitlyWait在抛出异常之前设置。 TimeUnit显示您想要等待的任何方式(秒、分、小时和天)。
其他回答
Use:
driver.manage().timeOuts().implicitlyWait(10, TimeUnit.SECONDS);
这意味着对网页上元素的任何搜索都需要时间来加载。implicitlyWait在抛出异常之前设置。 TimeUnit显示您想要等待的任何方式(秒、分、小时和天)。
下面是一个Java 8版本的目前被点赞最多的答案:
WebDriverWait wait = new WebDriverWait(myDriver, Duration.ofSeconds(15));
wait.until(webDriver -> "complete".equals(((JavascriptExecutor) webDriver)
.executeScript("return document.readyState")));
其中myDriver是一个WebDriver对象(前面声明过)。
注意:注意这个方法(document.readyState)只检查DOM。
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
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。 返回一个承诺,该承诺将在文档完成加载时得到解决。
我所见过的最好的方法是利用stalenessOf ExpectedCondition,等待旧页面变得陈旧。
例子:
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement oldHtml = driver.findElement(By.tagName("html"));
wait.until(ExpectedConditions.stalenessOf(oldHtml));
它将等待十秒钟,让旧的HTML标记变得陈旧,如果没有发生,则抛出异常。
推荐文章
- 在Selenium中等待页面加载
- Maven父pom vs模块pom
- 将JSON数据转换为Java对象
- Java的隐藏特性
- 使用Java 8的可选Stream::flatMap
- 使用管道字符("|")分割字符串
- 在IntelliJ中找不到Maven插件
- Java List.add() UnsupportedOperationException
- 连接两个字节数组的简单方法
- 为什么Mockito不模拟静态方法?
- Volatile boolean vs AtomicBoolean
- 在一个类中使用相同的方法实现两个接口。覆盖了哪个接口方法?
- 线程的上下文类装入器和普通类装入器之间的区别
- 如何在Java中正确地比较两个整数?
- 在Java中获取“unixtime”