如何让Selenium 2.0等待页面加载?
当前回答
你可以显式地等待一个元素出现在网页上,然后才可以采取任何操作(如element.click()):
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}
}
);
这是我用于类似场景的方法,效果很好。
其他回答
Ruby实现:
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until {
@driver.execute_script("return document.readyState;") == "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
如何让Selenium在单击后等待页面加载提供了以下有趣的方法:
存储旧页面中对WebElement的引用。 点击链接。 继续调用WebElement上的操作,直到抛出StaleElementReferenceException。
示例代码:
WebElement link = ...;
link.click();
new WebDriverWait(webDriver, timeout).until((org.openqa.selenium.WebDriver input) ->
{
try
{
link.isDisplayed();
return false;
}
catch (StaleElementReferenceException unused)
{
return true;
}
});
这似乎是WebDriver的一个严重限制。显然,等待一个元素并不意味着页面正在加载,特别是DOM可以完全构建(onready状态),此时JS仍在执行,CSS和图像仍在加载。
我相信最简单的解决方案是在onload事件上设置一个JS变量,在所有东西初始化后,在Selenium中检查和等待这个JS变量。
SeleniumWaiter:
import com.google.common.base.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniumWaiter {
private WebDriver driver;
public SeleniumWaiter(WebDriver driver) {
this.driver = driver;
}
public WebElement waitForMe(By locatorname, int timeout){
WebDriverWait wait = new WebDriverWait(driver, timeout);
return wait.until(SeleniumWaiter.presenceOfElementLocated(locatorname));
}
public static Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
// TODO Auto-generated method stub
return new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
};
}
}
对你来说:
_waiter = new SeleniumWaiter(_driver);
try {
_waiter.waitForMe(By.xpath("//..."), 10);
}
catch (Exception e) {
// Error
}
推荐文章
- 在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”