如何让Selenium 2.0等待页面加载?
当前回答
下面是一个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。
其他回答
/**
* Call this method before an event that will change the page.
*/
private void beforePageLoad() {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.mpPageReloaded='notYet';");
}
/**
* Call this method after an event that will change the page.
*
* @see #beforePageLoad
*
* Waits for the previous page to disappear.
*/
private void afterPageLoad() throws Exception {
(new WebDriverWait(driver, 10)).until(new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver driver) {
JavascriptExecutor js = (JavascriptExecutor) driver;
Object obj = js.executeScript("return document.mpPageReloaded;");
if (obj == null) {
return true;
}
String str = (String) obj;
if (!str.equals("notYet")) {
return true;
}
return false;
}
});
}
在只更改部分文档的情况下,您可以从文档更改为元素。
这个技巧的灵感来自于sincebasic的答案。
你也可以使用类:ExpectedConditions来显式地等待一个元素出现在网页上,然后你才能采取任何行动
你可以使用ExpectedConditions类来确定一个元素是否可见:
WebElement element = (new WebDriverWait(getDriver(), 10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input#houseName")));
查看ExpectedConditions类Javadoc,了解您可以检查的所有条件的列表。
在python中,你可以简单地使用:
driver.implicitly_wait(30)
我不认为含蓄的等待是你想要的。试试这个:
.timeouts driver.manage()()。TimeUnit.SECONDS pageLoadTimeout(10日);
更多信息请参见文档
使用类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")));
推荐文章
- 在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”