首页 > 解决方案 > 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 中是否有任何此类方法可用?或者有什么办法可以实现吗?到目前为止,我用谷歌搜索的内容一无所获。因此,任何帮助将不胜感激。

标签: javaseleniumxmlhttprequestwebdriverwait

解决方案


您可以定位 Element 并等待元素 selenium 中有隐式和显式等待。

你可以使用

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

或者

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

更多信息:关于这个答案


推荐阅读