【问题标题】:Selenium wait for specific XHR request to be completeSelenium 等待特定的 XHR 请求完成
【发布时间】: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


    【解决方案1】:

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

    你可以使用任何一个

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

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

    更多信息:on this answer

    【讨论】:

    • 是的,这始终是我的首选。但在我的情况下,有时这些元素已经存在,并且在请求后它们被更新,以及其他一些问题。因此,就我而言,等待特定请求的发出和加载是必不可少的。在这种情况下,等待元素失败。
    • 在这种情况下,您可以通过捕获请求并使用您喜欢的语言的 http 模块来实现自动化。
    猜你喜欢
    • 2018-11-28
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多