Java+Selenium3方法篇39-Explicit wait【转载】

本篇我们来讨论Selenium中Explicit wait,我自己翻译成中文的意思就是显式等待,我们很容易就想起了隐式等待implicitlyWait。我们前面介绍了implicitlyWait主要作用是只会检查页面元素展示的元素是否显示,如果该元素没有显示就会报错,提示该元素不可见。而Explicit wait就是设置一个最大时间的,如果超过这个时间,也会报错。主要是有以下场景,我们需要使用Explicit wait。

场景1:登录一个网站,输入用户名和密码后,点击登录,需要加载好几秒钟才能进入用户中心。例如你登录你网银,用户名和密码验证通过后,它需要等几秒,才能显示你账户信息,这几秒,它需要去数据库查询数据并显示在前端。

场景2:你登录一个旅行网站,填好了出发起点和目的地,点击搜索,需要查询等待几秒,然后给你显示车票信息。

       上面两个场景的几秒都是要必须等待的才能看见一些元素信息,这个时候,我们就可以考虑用Explicit wait,也就是显式等待方法。这里我们用苹果的icloud.com来演示。

[java] view plain copy
  1. package lessons;  
  2.   
  3. import java.util.concurrent.TimeUnit;  
  4.   
  5. import org.openqa.selenium.By;  
  6. import org.openqa.selenium.WebDriver;  
  7. import org.openqa.selenium.WebElement;  
  8. import org.openqa.selenium.firefox.FirefoxDriver;  
  9. import org.openqa.selenium.support.ui.ExpectedConditions;  
  10. import org.openqa.selenium.support.ui.WebDriverWait;  
  11.   
  12. public class ExplicitWait {  
  13.     public static void main(String[] args) throws Exception {    
  14.           
  15.         System.setProperty("webdriver.gecko.driver", ".\\Tools\\geckodriver.exe");    
  16.                 
  17.         WebDriver driver = new FirefoxDriver();    
  18.         driver.manage().window().maximize();    
  19.         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
  20.                 
  21.         driver.get("https://www.icloud.com/");    
  22.           
  23.         // 创建一个WebDriverWait类的一个对象 wait,设置5,默认单位是秒  
  24.         WebDriverWait wait=new WebDriverWait(driver,5);  
  25.           
  26.         // 等待知道5秒之后该元素还是不可见,就报错。  
  27.         driver.switchTo().frame("auth-frame");  
  28.         WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='appleId']")));  
  29.           
  30.         boolean status = element.isDisplayed();  
  31.            
  32.         // 判断  
  33.         if (status) {  
  34.             System.out.println("===== 元素可见======");  
  35.         } else {  
  36.             System.out.println("===== 元素不可见======");  
  37.         }  
  38.            
  39.     }  
  40. }  

       这个我测试5秒和2秒结构都打印元素可见,这个例子没有完全符合上面的场景。手动打开该网站,感觉要7 8秒才能看到icloud的登录界面。如果你想看到timeout的错误信息,你只需要把上面的xpath表达式随意改一下,就而已看到报错信息。

posted on 2018-05-03 11:10  okeymen  阅读(106)  评论(0)    收藏  举报

导航