Thread.sleep 和 webdriver.manage().timeouts().implicitlyWait的差别

来源:互联网 发布:mac英文全角 编辑:程序博客网 时间:2024/05/16 14:23
Thread.sleep() 是线程休眠若干秒,JAVA去实现。等待的时间需要预估的比较准确,但实际上这是很难做到。而且系统一直再等待,预估的长了,时间就白白的浪费了,预估短了,不起作用。
implicitlyWait() 不是休眠,是设置超时时间,是每个driver自己去实现的。以IEDriverServer为例,implicitlyWait()会将一个超时的时间阀值传递给IEDriverServer,在findelement或者findelements的时候,首先去找web元素,如果没有找到,判断时间否超超过implicitlyWait()传递进来的阀值,如果没有超过,则再次找这个元素,直到找到元素或者时间超过最大阀值。那我们就可以设定一个比较长的超时时间,但同时也不会让程序白白的等待。当然,在没有找到元素之后,IEDriverServer也是会休眠的,默认是250ms。
IEDriverServer 的部分源代码(selenium\cpp\IEDriver\CommandHandlers\FindElementCommandHandler.h):
int timeout = executor.implicit_wait_timeout();
      clock_t end = clock() + (timeout / 1000 * CLOCKS_PER_SEC);
      if (timeout > 0 && timeout < 1000)  {
        end += 1 * CLOCKS_PER_SEC;
      }
      int status_code = SUCCESS;
      Json::Value found_elements(Json::arrayValue);
      do {
        status_code = executor.LocateElements(ElementHandle(),
                                              mechanism,
                                              value,
                                              &found_elements);
        if (status_code == SUCCESS && found_elements.size() > 0) {
          response->SetSuccessResponse(found_elements);
          return;
        }
        if(status_code == EINVALIDSELECTOR) {
          response->SetErrorResponse(status_code,
            "The xpath expression '" + value + "' cannot be evaluated or does not" +
            "result in a WebElement");
          return;
        }
        if (status_code == EUNHANDLEDERROR) {
          response->SetErrorResponse(status_code,
            "Unknown finder mechanism: " + mechanism);
          return;
        }
          // Release the thread so that the browser doesn't starve.
          ::Sleep(FIND_ELEMENT_WAIT_TIME_IN_MILLISECONDS);
      } while (clock() < end);
原创粉丝点击