从这一节开始,不讲基本的页面操作了,开始为搭建框架做准备,例如如何封装查找元素的通用方法,这个方法封装好后其它类中都可以使用封装好的这个方法来查找元素,提高代码的复用性,方便后期维护。
一、首先我们需要封装一个能够定位元素的类
1 package usefulmethods; 2 3 import org.openqa.selenium.By; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 7 public class GenericMethods { 8 9 WebDriver driver; 10 // 创建一个构成方法,用于初始化对象 11 public GenericMethods(WebDriver driver) { 12 this.driver = driver; 13 } 14 15 public WebElement getElement(String type,String locator) { 16 if(type.equals("id")) { 17 System.out.println("用id查找元素:"+locator); 18 return this.driver.findElement(By.id(locator)); 19 }else if(type.equals("xpath")) { 20 System.out.println("用xpath查找元素:"+locator); 21 return this.driver.findElement(By.xpath(locator)); 22 }else if(type.equals("name")) { 23 System.out.println("用name查找元素:"+locator); 24 return this.driver.findElement(By.name(locator)); 25 }else if(type.equals("cssSelector")) { 26 System.out.println("用cssSelector查找元素:"+locator); 27 return this.driver.findElement(By.cssSelector(locator)); 28 }else if(type.equals("cssSelector")) { 29 System.out.println("用cssSelector查找元素:"+locator); 30 return this.driver.findElement(By.cssSelector(locator)); 31 }else if(type.equals("linkText")) { 32 System.out.println("用linkText查找元素:"+locator); 33 return this.driver.findElement(By.linkText(locator)); 34 }else if(type.equals("partialLinkText")) { 35 System.out.println("用partialLinkText查找元素:"+locator); 36 return this.driver.findElement(By.partialLinkText(locator)); 37 }else if(type.equals("tagName")) { 38 System.out.println("用tagName查找元素:"+locator); 39 return this.driver.findElement(By.tagName(locator)); 40 }else { 41 System.out.println("定位的路径不支持"); 42 return null; 43 } 44 } 45 }
二、对图中的输入框进行操作,输入“测试”(图中的页面是本地的网页,小伙伴们如果需要可以加入555191854下载或者找其它的网站进行练习)
package usefulmethods; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; class GenericMethodsDemo { private WebDriver driver; private String url; // 创建一个GenericMethods类的引用 private GenericMethods gm; @BeforeEach public void setUp() throws Exception { driver = new ChromeDriver(); // 实例化查找元素的方法 gm = new GenericMethods(driver); url = "C:\\\\Users\\\\acer\\\\eclipse-workspace\\\\SeleniumPractise\\\\PracticePage.html"; driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); } @Test public void test() { driver.get(url); // 通过调用GenericMethods类中的getElement方法,传入查找元素的方式和路径 WebElement el = gm.getElement("cssSelector", "#name"); el.sendKeys("测试"); } @AfterEach public void tearDown() throws Exception { Thread.sleep(2000); driver.quit(); } }
运行结果为:
如果有不明白的小伙伴可以加群“555191854”问我,群里都是软件行业的小伙伴可以相互一起学习讨论。