Selenium页面等待

1、隐式等待(implicitlyWait)

     等待页面全部元素加载完,一旦设置,会在WebDriver对象实例的整个生命周期起作用,所以只需要设置一次。

    示例:

 @Test

 publicvoidimplicitWait() {

      driver.get("http://www.baidu.com");

      try{

            driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);//使用implicitlyWait方法设置最大等待时间

           WebElementsearchButton=driver.findElement(By.id("query"));

          searchButton.click();

       }catch(NoSuchElementExceptione){

             Assert.fail("没有找到搜索按钮");

            e.printStackTrace();//打印错误的堆栈信息

       }

  }


2、显式等待(ExpectedConditions)


     直到元素出现后操作,如果超时则报异常。比隐式等待更节约时间

    示例:

 //显式等待

 @Test

 publicvoidexplicitWait() {

      driver.get("http://www.baidu.com");

       WebDriverWaitwait=newWebDriverWait(driver,10);//声明一个WebDriverWait对象,设定触发条件的最长等待时间为10秒

      try{

      wait.until(ExpectedConditions.titleContains("buzhi"));//调用ExpectedConditions的titleContions方法判断页面title属性是否包含“搜狗”两个字

       System.out.println("网页标题符合预期");

       }catch(NoSuchElementExceptione) {

            e.printStackTrace();

             System.out.println("网页标题不符合预期");

       }

  }


 //自定义的显式等待

   @Test(enabled=false)

 publicvoidtestExpliciWait() {

      driver.get(url1+"/");

      driver.findElement(By.id("query")).sendKeys("软件测试");

      try{

             WebElementtextInputBox= (newWebDriverWait(driver,3))

                       .until(newExpectedCondition(){

                 @Override   //重写父类(当注释用,可不写,可验证@Override下面的方法名是否是你父类中所有的)

                 publicWebElement apply(WebDriverd) {

                      returnd.findElement(By.xpath("//*[@type='text']"));

                  }

             });

             Assert.assertEquals("测试",textInputBox.getAttribute("value"));

       }

      catch(NoSuchElementExceptione) {

             Assert.fail("不符合预期");

            e.printStackTrace();

       }

  }

3、强制等待(Thread sleep)

     这种等待属于死等,很容易让线程挂掉,使程序抛异常。一般不建议使用。

示例:       Thread.sleep(3000);  //等待3秒

你可能感兴趣的:(Selenium页面等待)