如何停止执行selenium脚本一段时间?

时间:2017-10-26 19:36:16

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

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

    Thread.sleep();

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

3 个答案:

答案 0 :(得分:0)

如果您只是为了等待而等待(例如限制测试速度),而不期待任何其他条件发生,那么Thread.sleep()就是您所拥有的。

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

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

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

答案 1 :(得分:0)

这一直对我有用:

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

    }

答案 2 :(得分:0)

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);
    }
}
相关问题