自動化測試實施過程中,測試程序中常用的頁面操作有三個步驟
1.定位網頁上的頁面元素,並存儲到一個變量中
2.對變量中存儲的頁面元素進行操作,單擊,下拉或者輸入文字等
3.設定頁面元素的操作值,比如,選擇下拉列表中的那個下拉列表或者輸入框中輸入什麼值
其中定位頁面元素是三步驟的第一步,本篇介紹常用的定位方法
webDriver對象的findElement函數用於定位一個頁面元素,findElements函數用戶定位多個頁面元素,定位的頁面元素使用webElement對象進行存儲
常用的方法有:
1.使用ID定位
driver.findElement(By.id("ID值")); WebElement element = driver.findElement(By.id("username"));
2.使用name定位
driver.findElement(By.name("name值")); WebElement element = driver.findElement(By.name("username"));
3.使用鏈接的全部文字定位
driver.findElement(By.linkText("鏈接的全部文字內容")); driver.findElement(By.linkText("我的項目"));
4.使用部分鏈接文字定位
driver.findElement(By.partialLinkText("鏈接的部分文字內容")); driver.findElement(By.partialLinkText("項目"));
5.使用xPath方式定位
XPATH是一門在XML文檔中查找信息的語言,它是XML Path的簡稱. XPATH可用來在XML文檔中對元素和屬性進行遍歷,提供了瀏覽樹的能力
這個方法是非常強大的元素查找方式,使用這種方法幾乎可以定位到頁面上的任意元素.
瀏覽器都自帶html導出xPath的功能
這裏導出的xPath爲://*[@id="lst-ib"]
1.xPath絕對定位
查找value值爲button的div
webElement button = driver.findElement(By.xpath("/html/body/div/input[@value='查詢']"));
使用絕對路徑方式是十分脆弱的,因爲即便也買你代碼發生了微小的變化,也會造成原有的xPath表達式定位失敗
2.使用相對路徑定位
webElement button = driver.findElement(By.xpath("//div/input[@value='查詢']"));
實用舉例:
查詢第二個input,xPath是從1開始的
driver.findElement(By.xpath("//input[2]"));
定位頁面的第一張圖片
driver.findElement(By.xpath("//img[@href='xxx']"));
定位第二個div中第一個input輸入框
driver.findElement(By.xpath("(//div[@class='mob-share-list'])[2]/input[1]"));
模糊定位:start-with
尋找rel屬性以ahaha開頭的a元素
driver.findElement(By.xpath("//a[starts-with(@rel,'ahaha')]"));
模糊定位:contains
需找內容含有提交二字的button
driver.findElement(By.xpath("//button[contains(text(),'提交')]"));
尋找rel屬性包含ahaha的a元素
driver.findElement(By.xpath("//a[contains(@rel,'ahaha')]"));
5.使用css方式定位
driver.findElement(By.cssSelector("css定位表達式")); driver.findElement(By.cssSelector("img.plusImg")); driver.findElement(By.cssSelector("input[type='button']")); driver.findElement(By.cssSelector("input#div1input"));//根據id的屬性值 driver.findElement(By.cssSelector("Img[alt='img1'][href='http://www.sougou.com']"));
6.使用class名稱定位
driver.findElement(By.className("頁面的class屬性值")); driver.findElement(By.className("tight left"));//要寫全
7.使用標籤名稱定位
driver.findElement(By.tagName("頁面的html標籤名稱"));
webElement element = driver.findElement(By.tagName("a")); list<webElement> elements = driver.findElements(By.tagName("a"));
8.使用js表達式
((JavascriptExecutor) driver).executeScript("js表達式"); JavascriptExecutor js1 = (JavascriptExecutor) driver; js1.executeScript("document.getElementsByClassName(\"ke-edit-iframe\")[0].setAttribute(\"name\",\"frame-name\")");