Selenium 与 DOM 的交互似乎非常缓慢,而在每个页面实例化中都做一些事情。在整个站点中,我们都有可见的微调器,指示任何未解决的 API 调用是否已解决。总之,我有三种方法可以在执行任何操作之前确保页面的稳定性。
- 检查 DOM 就绪状态
- 检查任何未完成的 JQuery 调用
- 检查加载微调器
所有这三个都是通过以下方法作为页面对象实例化的一部分完成的。
public static void waitForLoadingAllSpinnersAnywhere(final WebDriver driver){
final WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(waitForDomReadyState());
wait.until(waitForjQueryToBeInactive());
List<WebElement> elements = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(spinnersLoacator));
for(WebElement element: elements){
wait.until(invisibilityOfElementLocated(element));
}
}
private static ExpectedCondition<Boolean> waitForDomReadyState(){
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver d){
return ( ((JavascriptExecutor) d).executeScript("return document.readyState;").equals("complete"));
}
};
}
private static ExpectedCondition<Boolean> waitForjQueryToBeInactive(){
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver d){
return (Boolean) ( ((JavascriptExecutor) d).executeScript("return jQuery.active == 0;"));
}
};
}
public static ExpectedCondition<Boolean> invisibilityOfElementLocated(final WebElement element){
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver){
try{
return !element.isDisplayed();
} catch (NoSuchElementException | StaleElementReferenceException e){
// Returns true because the element is not present in DOM.
// The
// try block checks if the element is present but is
// invisible or stale
return true;
}
}
};
}
以具有大量 API 调用并获取大量数据的页面(例如患者页面)为例。对于初始类实例化,大约需要 17 秒(日志如下)。我的 Selenium 知识表明,后续页面实例化不应花费相同或更多的时间来检查 DOM 就绪状态,或者 JQuery 调用或微调器等待,因为根本没有任何变化。但是,每次新页面实例化时,我都会看到检查所有这三个页面所花费的时间相同。那里发生了什么?每次我执行这些操作时,Selenium 是否实际上都尝试与服务器交互,或者由于某种原因,与客户端的交互速度很慢?如果是这样,可能的答案是什么?
控制台日志
==== [[在 [17] 秒后等待小部件 [Patient] 上的 8 个微调器元素完成等待]]
==== [[开始等待在小部件 [Patient] 上找到 8 个微调器元素]]
==== [[在 [17] 秒后等待小部件 [Patient] 上的 8 个微调器元素完成等待]]
==== [[[患者]]] 上的浏览器
==== [[开始等待在小部件 [Patient] 上找到 8 个微调器元素]]
==== [[在 [17] 秒后等待小部件 [Patient] 上的 8 个微调器元素完成等待]]
环境:
- 硒 2.48
- 火狐 38
我也尝试过使用 Selenium 2.52 和 firefox 44,结果相同