显示等待与隐式等待

强制等待

Thread.sleep(5000);

隐式等待

//添加隐式等待
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

显式等待

  • 必须: 每个需要等待的元素前面进行声明
  • 针对的是某个条件的等待时间,在设置的时间内,可以默认每隔一段时间也可以指定每隔多久去检查一次条件是否满足
  • 默认的检测频率0.5s;

显示等待声明

  • webDriver: 当前的driver 驱动AndroidDriver、ChromeDriver
  • timeout: 显示等待的总时间,最长超时时间
  • sleeper: 每隔多久就去检查一下对应的显示等待条件,默认500s
  • TimeoutException: 默认抛出的异常

显示等待传入条件

  • until(// 等待条件):
  • 等待期间,每隔一段时间「sleeper」 就会调一下等待条件,直到返回值不是false

显示等待传入报错message

  • withMessage(“报错message”):
  • 返回值false对应的报错信息

ExpectedConditions

  • presenceOfElementLocated:
    • 元素在页面是否存在,不一定显示可见,只要在dom树存在即可。
    • 如果存在,则返回true
      ExpectedConditions.presenceOfElementLocated(AppiumBy.xpath(""))
  • visibilityOfElementLocated: 元素是否可见
    • 元素在页面是否可以肉眼可见
      ExpectedConditions.visibilityOfElementLocated(AppiumBy.xpath(""))
  • invisibilityOfElementLocated: 元素是否不可见
    ExpectedConditions.invisibilityOfElementLocated(AppiumBy.xpath(""))
  • elementToBeClickable: 元素是否可点击
    • 如果元素可以点击,则返回true
      ExpectedConditions.elementToBeClickable(AppiumBy.xpath(""))

Lambda

  • 不用lambda方式声明,直接使用另声明一个driver
Function<WebDriver, Object> function=new Function<>(){
    @Override
    public Object apply(WebDriver webDriver){
        return webDriver.findElement(hot);
    }
};
FluentWait<WebDriver> withMessage=webDriver.withMessage("查找失败");
withMessage.until(function);
  • lambda简写
webDriverWait.withMessage("查找失败").until(webDriver -> webDriver.findElement(hot));

//显示等待
WebElement element=new WebDriverWait(driver,Duration.ofSeconds(3))
.until(ExpectedConditions.visibilityOfElementLocated(
AppiumBy.id(“com.xueqiu.android:id/home_search”)));
element.click();

流式等待

@Test
    void fluentWaitTest(){
        //流式等待
        FluentWait wait =new FluentWait(driver)
                //设置等待评估条件为真的时间 --超时总值
                .withTimeout(Duration.ofSeconds(45))
                //设置评估条件的频率 -- 轮询频率
                .pollingEvery(Duration.ofSeconds(3))
                // 忽略特定类型的异常
                .ignoring(NoSuchElementException.class);
        WebElement element = (WebElement) wait.until(new Function<AndroidDriver,WebElement>() {
            @Override
            public WebElement apply(AndroidDriver driver) {
                return driver.findElement(AppiumBy.id("com.xueqiu.android:id/home_search"));
            }
        });
        element.click();
        driver.findElement(AppiumBy.id("com.xueqiu.android:id/search_input_text")).sendKeys("alibaba");

        try {
            sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }