【问题标题】:How can I halt execution of a selenium script for a while?如何暂停硒脚本的执行一段时间?
【发布时间】:2017-10-26 19:36:15
【问题描述】:

我正在运行 Selenium 脚本。我想暂停脚本的执行一段时间。 我不想使用 selenium implicitexplicit wait,因为我不是在等待页面转换或元素出现或满足条件。 据我所知,

    Thread.sleep();

通常用于这种情况。除了 Thread.sleep() 还有其他方法吗?

【问题讨论】:

  • 你想要完成什么?你想等待用户输入吗?您想等待而不进行异常处理吗?
  • @BillHileman 我只是想在完成任何其他操作之前查看页面是否已正确加载并且所有元素都符合预期。使用 Thread.sleep() 经常会出现一些性能问题。所以我只想知道是否有替代方案。

标签: java selenium selenium-webdriver wait thread-sleep


【解决方案1】:

这一直对我有用:

public static void waitForPageToLoad() {

        WebDriverWait wait = new WebDriverWait(driver, 15);

        wait.until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver wdriver) {
                return ((JavascriptExecutor) driver).executeScript(
                    "return document.readyState"
                ).equals("complete");
            }
        }); 

    }

【讨论】:

  • 所以这个显式等待一直等到页面完全加载。是对的吗?还是我错过了什么?
  • 它一直等到文档返回 :ready" 的状态,这并不完美,但它已经尽可能接近了。关于唯一可以干扰它的东西是 ajax,这是另一个故事。
  • 我提供的这个解决方案对您有用吗?如果是这样,您能否将其标记为已接受的答案?
【解决方案2】:

如果您只是为了等待而等待(例如限制测试速度),并且不希望发生任何其他情况,那么 Thread.sleep() 就是您所拥有的一切。

如果您正在寻找替代方案:在过去,在 .sleep() 之前,您只需创建一个什么都不做的 for 循环:

for(int i = 0; i < 1000000; i++) {
    // wait
}

但是,这并不完全可靠,因为您无法保证从一台机器到另一台机器的持续时间。这样的代码甚至可能会被优化掉。

【讨论】:

    【解决方案3】:

    Thread.sleep() 似乎是完成您特别要求的唯一方法。

    这是实现它的适当方法:

    /**
     * Pause the test to wait for the page to display completely.
     * This is not normally recommended practice, but is useful from time to time.
     */
    public void waitABit(final long delayInMilliseconds) {
        try {
            Thread.sleep(delayInMilliseconds);
        } catch (InterruptedException e) {
            LOGGER.warn("Wait a bit method was interrupted.", e);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-05
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 2020-02-21
      • 2019-08-14
      • 1970-01-01
      相关资源
      最近更新 更多