如何暂时停止执行 selenium 脚本?

How can I halt execution of a selenium script for a while?

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

    Thread.sleep();

一般用于这种情况。除了 Thread.sleep()?

还有其他方法吗?

如果您只是为了等待而等待(例如限制测试速度),而不期望发生任何其他情况,那么 Thread.sleep() 就是您的全部。

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

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

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

这对我一直有效:

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");
            }
        }); 

    }

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);
    }
}