Selenium 显式等待设置间隔时间

Selenium explicit wait set interval time

在我的自动化脚本中,我使用显式等待来处理等待时间

wait = new WebDriverWait(driver, Duration.ofSeconds(45000));
    
    public WebElement waitVisibility(By by) {
            return wait.until(ExpectedConditions.visibilityOfElementLocated(by));
        }

现在有时我会收到找不到元素的错误消息,因为某些弹出消息出现的时间很短。

error is like (tried for 40 second(s) with 500 milliseconds interval)

这里我的问题是如何将拉取时间从 500 毫秒减少到 200 毫秒

如您所见,Selenium WebDriverWait 默认设置为每 500 毫秒轮询一次 DOM。我们可以使用 pollingEvery 方法覆盖此设置。
这可以按如下方式完成:

public WebElement waitVisibility(By by) {
    WebDriverWait wait = new WebDriverWait(driver, 40);
    wait.pollingEvery(200, TimeUnit.MILLISECONDS);
    return wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}

要配置轮询之间的休眠持续时间,您可以使用以下constructor of

public WebDriverWait​(WebDriver driver, java.time.Duration timeout, java.time.Duration sleep)

Wait will ignore instances of NotFoundException that are encountered (thrown) by default in the 'until' condition, and immediately propagate all others. You can add more to the ignore list by calling ignoring(exceptions to add).

Parameters:

  • driver - The WebDriver instance to pass to the expected conditions
  • timeout - The timeout in seconds when an expectation is called
  • sleep - The duration in milliseconds to sleep between polls.

实施:

wait = new WebDriverWait(driver, Duration.ofSeconds(45000), Duration.ofMilliSeconds(200));

    public WebElement waitVisibility(By by) {
        return wait.until(ExpectedConditions.visibilityOfElementLocated(by));
    }