【发布时间】:2021-01-04 00:56:55
【问题描述】:
您好,我正在做一个 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 文档并找到了这个。根据 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 中有没有这样的方法可用?或者有什么办法可以实现吗?到目前为止,我搜索的内容一无所获。因此,我们将不胜感激。
【问题讨论】:
标签: java selenium xmlhttprequest webdriverwait