1、封裝一個包含了一個指望條件的類(顯示等待的指望條件有不少,此處用於舉例)css
1 package utility; 2 3 import org.openqa.selenium.By; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 import org.openqa.selenium.support.ui.ExpectedConditions; 7 import org.openqa.selenium.support.ui.WebDriverWait; 8 9 public class WaitTypes { 10 11 WebDriver driver; 12 public WaitTypes(WebDriver driver) { 13 this.driver = driver; 14 } 15 16 // 封裝了一個顯式等待的方法,裏面包含等待元素可用時再繼續執行操做,不然打印異常信息 17 public WebElement waitForElement (By locator,int waitTime) { 18 WebElement element = null; 19 // 不使用try、catch來捕獲異常,若是代碼有問題執行就會中斷,沒法繼續執行後面的代碼 20 try{ 21 System.out.println("最長等待了"+waitTime+"秒元素可用"); 22 WebDriverWait wait = new WebDriverWait(driver,waitTime); 23 element = wait.until( 24 ExpectedConditions.visibilityOfElementLocated(locator)); 25 System.out.println("元素在頁面上出現了"); 26 }catch(Exception e){ 27 System.out.println("元素沒有在頁面上出現"); 28 } 29 return element; 30 } 31 }
全部指望條件有:https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.htmlhtml
2、調用封裝的顯示等待方法java
1 package utility; 2 3 import org.junit.jupiter.api.AfterEach; 4 import org.junit.jupiter.api.BeforeEach; 5 import org.junit.jupiter.api.Test; 6 import org.openqa.selenium.By; 7 import org.openqa.selenium.WebDriver; 8 import org.openqa.selenium.WebElement; 9 import org.openqa.selenium.ie.InternetExplorerDriver; 10 import org.openqa.selenium.support.ui.ExpectedConditions; 11 import org.openqa.selenium.support.ui.WebDriverWait; 12 13 class ExplicitWaitWithUtilityDemo { 14 private WebDriver driver; 15 private String url; 16 // 聲明一下這個類的對象 17 private WaitTypes wait; 18 19 @BeforeEach 20 void setUp() throws Exception { 21 driver = new InternetExplorerDriver(); 22 // 實例化已經封裝好的顯式等待方法 23 wait = new WaitTypes(driver); 24 url = "https://www.yahoo.com/"; 25 driver.manage().window().maximize(); 26 // 隱式等待3秒 27 // driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); 28 } 29 30 @Test 31 void test() { 32 driver.get(url); 33 WebElement el = driver.findElement(By.id("uh-signin")); 34 el.click(); 35 // 直接調用封裝好的顯式等待方法 36 WebElement emailField = wait.waitForElement(By.cssSelector("#login-username"), 2); 37 emailField.sendKeys("test"); 38 // driver.findElement(By.cssSelector("#login-username")).sendKeys("test"); 39 } 40 41 @AfterEach 42 void tearDown() throws Exception { 43 Thread.sleep(2000); 44 driver.quit(); 45 } 46 }
運行結果:git
若是有不明白的小夥伴能夠加羣「555191854」問我,羣裏都是軟件行業的小夥伴能夠相互一塊兒學習討論。github