Selenium 隐式等待总是占用整个等待时间还是可以更快完成?

Does Selenium implicit wait always take the entire wait time or can it finish sooner?

Selenium 隐式等待总是占用整个等待时间还是可以更快完成?如果我将隐式等待设置为 10 秒,对 .findElement 的调用可以在几秒钟内完成,还是总是需要整个 10 秒?

This page 意味着它等待整整 10 秒,这非常令人困惑,因为它不是 javadoc 所暗示的。

来自 WebDriver.java 的以下代码注释暗示它是一个可以比定义的隐式超时更快完成的轮询操作。但是,评论中的最后一句话确实打破了这种信念,让我对此不太确定。如果它实际上是在轮询,那么它会如何 "adversely affect test time",因为它不会耗尽整个隐式等待时间?

/**
 *  from WebDriver.java
 * Specifies the amount of time the driver should wait when searching for an element if
 * it is not immediately present.
 * <p/>
 * When searching for a single element, the driver should poll the page until the 
 * element has been found, or this timeout expires before throwing a 
 * {@link NoSuchElementException}. When searching for multiple elements, the driver 
 * should poll the page until at least one element has been found or this timeout has
 * expired.
 * <p/>
 * Increasing the implicit wait timeout should be used judiciously as it will have an 
 * adverse effect on test run time, especially when used with slower location 
 * strategies like XPath.
 * 
 * @param time The amount of time to wait.
 * @param unit The unit of measure for {@code time}.
 * @return A self reference.
 */
Timeouts implicitlyWait(long time, TimeUnit unit);

此外,是否有人可以提供有关默认 "polling" 发生频率的信息?

如代码注释所述:

 * When searching for a single element, the driver should poll the page until the 
 * element has been found, or this timeout expires before throwing a 
 * {@link NoSuchElementException}.

它将等到该元素出现或发生超时。

例如,如果将隐式等待设置为 10 秒,.findElement 将为该元素等待最多 10 秒。假设 5 秒后 DOM 中可用的元素,则它会从 "wait" 中出来并开始执行下一步。

希望这能澄清。

一旦能够找到元素,它就可以完成。如果不是,它会抛出错误并停止。轮询时间再次非常特定于驱动程序实现(不是 Java 绑定,而是驱动程序部分,例如:FireFox 扩展、Safari 扩展等)

正如我提到的 ,这些都是针对驱动程序实现的。所有与驱动程序相关的调用都通过 execute 方法进行。

我将介绍 execute 方法的要点(您可以找到完整的来源 here):

protected Response execute(String driverCommand, Map<String, ?> parameters) {
    Command command = new Command(sessionId, driverCommand, parameters);
    Response response;

    long start = System.currentTimeMillis();
    String currentName = Thread.currentThread().getName();
    Thread.currentThread().setName(
        String.format("Forwarding %s on session %s to remote", driverCommand, sessionId));
    try {
      log(sessionId, command.getName(), command, When.BEFORE);
      response = executor.execute(command);
      log(sessionId, command.getName(), command, When.AFTER);

      if (response == null) {
        return null;
      }
      //other codes 
}

行:

response = executor.execute(command);

说来话长。 executor 属于 CommandExecutor 类型,因此所有调用都转到特定驱动程序 class,如 ChromeCommandExecutor,SafariDriverCommandExecutor,它有自己的处理方式。

所以轮询取决于驱动程序的实现。

如果你想指定轮询时间,那么你应该开始使用Explicit Waits

据我所知,隐式等待的轮询周期不是 0.5 秒。显式等待就是这种情况。显式等待每 500 毫秒轮询一次 DOM。隐式等待,如果在页面加载时未找到元素,则等待指定的时间,然后在时间 运行 结束后再次检查。如果找不到它会抛出一个错误