java - Selenium 等待特定的 XHR 请求完成
问题描述
嗨,我正在做一个 selenium 项目,我遇到的最大困难是等待 XHR 请求完成。我目前正在做的是等待使用以下预期条件发出请求,
public ExpectedCondition<Boolean> jQueryExpect (int expectedActive) {
ExpectedCondition<Boolean> jQLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver dr) {
try {
logger.log(Level.INFO,"Checking number of jQueries Active");
Long active = (Long) ((JavascriptExecutor) driver).executeScript("return jQuery.active");
logger.log(Level.INFO,"jQuery''s active: {0}",active);
return (active >= expectedActive);
}
catch (Exception e) {
logger.log(Level.WARNING,"Error executing script in jQueryLoad method");
// no jQuery present
return true;
}
}
};
return jQLoad;
}
然后我等待jQuery使用这个预期的条件加载
public ExpectedCondition<Boolean> jQueryLoad (int expectedActive) {
ExpectedCondition<Boolean> jQLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver dr) {
try {
logger.log(Level.INFO,"Checking number of jQueries Active");
Long active = (Long) ((JavascriptExecutor) driver).executeScript("return jQuery.active");
logger.log(Level.INFO,"jQuery''s active: {0}",active);
return (active <= expectedActive);
}
catch (Exception e) {
logger.log(Level.WARNING,"Error executing script in jQueryLoad method");
// no jQuery present
return true;
}
}
};
return jQLoad;
}
这个方法现在工作得很好,因为我知道有多少请求。但是正如您已经注意到的那样,随着请求的数量由于某种原因发生变化,它很容易在未来中断。
我一直在查看 cypress 文档并发现了这一点。根据赛普拉斯文档,这会等待指定的请求。
cy.wait(['@getUsers', '@getActivities', '@getComments']).then((xhrs) => {
// xhrs will now be an array of matching XHR's
// xhrs[0] <-- getUsers
// xhrs[1] <-- getActivities
// xhrs[2] <-- getComments
})
Selenium 中是否有任何此类方法可用?或者有什么办法可以实现吗?到目前为止,我用谷歌搜索的内容一无所获。因此,任何帮助将不胜感激。
解决方案
您可以定位 Element 并等待元素 selenium 中有隐式和显式等待。
你可以使用
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
或者
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
更多信息:关于这个答案
推荐阅读
- pointers - go - 修改指向切片的指针不会修改原始指针
- java - 在视图之间导航后,组件未正确加载
- php - 使用没有数据库的身份验证登录
- node.js - Angular 前端不会立即更新
- java - 在个人资料活动中滚动查看
- html - 下拉菜单在点击前消失
- docker - kube-proxy 问题 - 尝试将 Windows 工作节点添加到 kubernetes 集群
- tomcat8 - Ubuntu 服务器 18.04.2 上的 Tomcat 8.5.39
- java - 如何从 github 的几个页面中获取用户存储库
- php - Laravel 无法使用 DB::getDatabaseName() 获取正确的数据库名称