一、封装一个包含了一个期望条件的类(显示等待的期望条件有很多,此处用于举例)
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.html
二、调用封装的显示等待方法
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 }
运行结果:
如果有不明白的小伙伴可以加群“555191854”问我,群里都是软件行业的小伙伴可以相互一起学习讨论。