Selenium WebDriver
1.WebDriver介紹
Selenium 2.0最主要的新特性就是集成了WebDriver API。我們設計WebDriver的初衷是提供更加簡單明了的接口來彌補Selenium-RC API的不足。在動態網頁中,通常只會更新局部的html元素,WebDriver會很好的幫助用戶快速定位這些元素。我們最終的目的是通過提供精心設計的面向對象API來解決現代高級網頁中的測試難題。
2.WebDriver如何驅動瀏覽器?與Selenium-RC有什么區別?
不同類型的瀏覽器都會有原生的接口支持自動化操作,Selenium通過這些接口直接向瀏覽器發送指令。如何發送這些指令取決于你當前使用的瀏覽器類型,我們將在這一章節后面來詳細介紹。
看上去WebDriver與之前Selenium-RC的實現方式類似,實際上兩者之間存在著本質的區別。對于所有類型的瀏覽器Selenium-RC都是使用的同一種方法:當瀏覽器啟動時,向其中注入javascript,從而使用這些js來驅動瀏覽器中的AUT(Application Under Test)。WebDriver并沒有使用這種技術,它是通過調用瀏覽器原生的自動化API直接驅動瀏覽器。
3.WebDriver與Selenium Server
是否需要是用Selenium Server取決于你使用WebDriver的方式。以下兩種情況不需要使用Selenium Server,WebDriver直接運行瀏覽器即可:1、testcases僅僅使用了Webdriver的API;2、瀏覽器和testcase在同一臺PC上,而且testcases僅僅使用了Webdriver的API。
以下三種情況你需要結合Selenium Server來使用WebDriver:
1)使用Selenium-Grid管理集群環境(或者虛擬機)上的testcase;
2)需要調用非本機上的不同版本的瀏覽器;
3)未使用任何language binding(java/c#/python/ruby),且有意向使用HtmlUnitDriver。
4.配置Selenium-WebDriver工程
首先,創建一個文件夾存放Maven工程文件。然后,創建pom.xml,你可以使用text editor來編輯。鑒于已經有很多關于“如何在Maven工程中使用pom.xml”優秀的參考文獻,這里將不再過多的討論相關細節。下面給出一個示例,為你的工程也創建一個類似的文件。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>MySel20Proj</groupId> <artifactId>MySel20Proj</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.38.0</version> </dependency> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> <version>1.5</version> <exclusions> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-remote-driver</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </dependencyManagement> </project>請確認你使用的WebDriver是最新的當前版本。在這篇文檔撰寫時,上述示例給出的是最新的版本。在Selenium2.0發布不久WebDriver就有過頻繁的更新。請在這個鏈接 Maven Download Page 確認當前的版本,相應地修改你工程中的pon.xml。
現在,你可以通過dos界面使用CD命令進入工程所在文件夾,通過以下命令運行Maven。
?
mvn clean install
?
運行之后會自動下載Selenium及相關套件,并加載到你的工程中去。
最后,將你的工程導入到你偏好的IDE中。如果你對導入的過程不是很清楚,我們已經準備了操作指南。
Importing a maven project into IntelliJ IDEA . Importing a maven project into Eclipse
5.如何將自動化工程從Selenium1.0遷移到Selenium2.0
已經在Selenium1.0上構建測試工程的用戶,我們為您提供了一份指導如何將已有的代碼遷移到Selenium2.0。Selenium2.0的首席開發工程師Simon Stewart為此撰寫了一片文章: Magrating From Selenium RC to Selenium WebDriver 。
6.Selenium-WebDriver API簡介
現在你肯定躍躍欲試要寫一些代碼了。我們以一個簡單的例子來開始第一段旅程:在Google上搜索“Cheese”,并打印出搜索結果網頁的標題。
?
package org.openqa.selenium.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class Selenium2Example { public static void main(String[] args) { // 創建一個FirefoxDriver實例 // 這個類依賴于接口而不是接口的實現 WebDriver driver = new FirefoxDriver(); // 使用get方法訪問Google driver.get("http://www.google.com"); // 使用下面這個方法也能夠達到訪問Google的目的 // driver.navigate().to("http://www.google.com"); // 找到html輸入框的name WebElement element = driver.findElement(By.name("q")); // 輸入要查找的內容 element.sendKeys("Cheese!"); // 提交表單,WebDriver會自動找到我們需要提交的元素所在的表單 element.submit(); // 打印網頁的標題 System.out.println("Page title is: " + driver.getTitle()); // Google的搜索網頁會通過JS動態渲染 // 等待頁面加載完畢,超時時間為10秒 (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().startsWith("cheese!"); } }); // 控制臺上將打印如下信息: "cheese! - Google Search" System.out.println("Page title is: " + driver.getTitle()); // 關閉瀏覽器 driver.quit(); } }
在本章節的接下來篇幅,我們將學習如何使用WebDriver操作你的瀏覽器,如何使用框架和窗口來測試Web網站。當然,我們將提供更加翔實的論述和舉例。
?
7.Selenium-WebDriver API詳解
7.1獲取Web頁面
driver.get("http://www.google.com");在某些情況下,比如操作系統和瀏覽器的穿插組合,WebDriver有可能不會等待Web頁面加載完成,這種情況下WebDriver會返回錯誤或者直接運行下一步操作。為了保證程序的健壯性,你需要等待頁面中某個元素加載完成后再進行下一步操作,請參考 Explicit and Implicit Waits 。
7.2定位UI元素
<div id="coolestWidgetEvah">...</div> WebElement element = driver.findElement(By.id("coolestWidgetEvah"));
?
By Class Name
在這種場景下,我們引用DOM元素的屬性。實際情況是很多元素都有一樣的Class Name,因此找到多個有相同Class Name的元素,比找到第一個擁有這個Class Name的元素來的更重要。
示例:如何使用該方法定位元素
?
<div class="cheese"><span>Cheddar</span></div><div class="cheese"><span>Gouda</span></div> List<WebElement> cheeses = driver.findElements(By.className("cheese"));
By Tag Name
?
DOM元素Tag的名稱。
示例:如何使用該方法定位元素
?
<iframe src="..."></iframe> WebElement frame = driver.findElement(By.tagName("iframe"));
By Name
?
找到與Name屬性相同的Input元素。
示例:如何使用該方法定位元素
?
<input name="cheese" type="text"/> WebElement cheese = driver.findElement(By.name("cheese"));
By Link Text
?
找到與Text屬性精確匹配的超鏈接。
示例:如何使用該方法定位元素
?
<a >cheese</a> WebElement cheese = driver.findElement(By.linkText("cheese"));
By Partial Link Text
?
找到與Text屬性模糊匹配的超鏈接。
示例:如何使用該方法定位元素<a >search for cheese</a> WebElement cheese = driver.findElement(By.partialLinkText("cheese"));
By CSS
示例:如何使用該方法定位元素
?
<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div> WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));
By XPath
當有需要時,WebDriver還可以使用瀏覽器自帶的XPATH。對于那些不支持XPATH的瀏覽器,我們提供了WebDriver特有的實現方式。請確保熟悉XPATH在不同的引擎中的區別,否則會導致一些不可預料的問題。
Driver | 大小寫敏感 | 屬性值是否可見 | 是否支持XAPTH |
HtmlUnit Driver | 僅識別小寫 | 可見 | 是 |
IE Driver | 僅識別小寫 | 可見 | 否 |
FireFox Diver | 大小寫不敏感 | 可見 | 是 |
上面的表格有一些抽象,讓我們來看個例子
?
<input type="text" name="example" /> <INPUT type="text" name="other" /> List<WebElement> inputs = driver.findElements(By.xpath("http://input"));
匹配結果如下
?
XPATH表達式 | HtmlUnit Driver | FireFox Driver | IE Driver |
//input | 1 | 2 | 2 |
//INPUT | 0 | 2 | 0 |
有些標簽的屬性有默認值,這種情況下不指定屬性值則匹配默認值。比如,"input"標簽"type"屬性默認為"text"。使用XPATH的首要原則就是不要忽略這些隱藏的實現。
使用JavaScript
只要返回的是一個Web Element,你還可以使用任意的JS代碼查找Web元素,根據查詢結果會自動修改為一個WebElement對象。
一個簡單的使用jQuery的例子:
?
WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]");
查找頁面中每個label的所有Input元素:
?
?
List<WebElement> labels = driver.findElements(By.tagName("label")); List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript( "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" + "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
?
?
7.3模擬用戶輸入行為
WebElement select = driver.findElement(By.tagName("select")); List<WebElement> allOptions = select.findElements(By.tagName("option")); for (WebElement option : allOptions) { System.out.println(String.format("Value is: %s", option.getAttribute("value"))); option.click(); }
上面的例子,將選擇Web頁面中的第一個Select元素,并將循環打印出選項的取值并單擊選項?;蛟S你已經注意到,使用這個方法并不是最有效的。WebDriver提供一個“Select”類,這個類的方法更適合于處理上述這種場景。
Select select = new Select(driver.findElement(By.tagName("select"))); select.deselectAll(); select.selectByVisibleText("Edam");
上面的例子,首先去除選定第一個選項的焦點,然后選中取值為"Edam"的選項。
driver.findElement(By.id("submit")).click();
作為另一種選擇,WebDriver的Element類有一個更加便利的方法"sublmit"。如果你對表單中的某個Element使用該方法,WebDriver將會走讀其所在的DOM對象,直到找到其所屬的表單,并提交。如果該Element并不在某個表單中,將會拋出異常NoSuchElementException。
element.submit();
7.4在windows和frames間切換
driver.switchTo().window("windowName");
所有傳輸給WebDriver的指定將被傳輸給切換后的窗口。如何直到窗口的名稱呢?查看JS并打開該窗口就可以了:
<a href="somewhere.html" target="windowName">Click here to open a new window</a>
作為另一種選擇,你可以使用一個“窗口句柄”傳遞給"switchTo().window()"方法。根據此方法,將會使用迭代器遍歷所有打開的窗口:
for (String handle : driver.getWindowHandles()) { driver.switchTo().window(handle); }
你也可以在Frame之間切換(或者進入Frame):
driver.switchTo().frame("frameName");
你還可以根據路徑使用Frame的子Frame,而且可以通過索引定位Frame。
driver.switchTo().frame("frameName.0.child");以上方法將切換到名稱為“frameName”的Frame的第一個子Frame,所有Frame都是Web頁面的最頂端開始計數。
7.5彈出框
Alert alert = driver.switchTo().alert();
以上方法將會返回當前當前打開的alert對象,你可以對這個對象進行任何可操作:點擊取消,點擊確定,關閉窗口,獲取alert的文本內容等。這個接口在alerts、confirms、prompts對象上都有很好的應用,具體請參見API文檔。
?
7.6Navigation:瀏覽器本地歷史記錄
?
前文中,我們使用get方法來獲取網頁( driver.get("http://www.example.com") )。正如你看到的,WebDriver有不少輕量級的功能聚焦的接口,Navigation就是這樣一個。正因為加載網頁是一個再普通不過的需求,這個方法存在于Driver類下面,但是用法很簡單:
?
driver.navigate().to("http://www.example.com");
重申一下,"navigate().to()"和"get()"做的是同樣的事情,只不過其中一個更適合打印。
?
Navigate接口還提供方法可以在瀏覽器歷史記錄中前后翻頁。
?
driver.navigate().forward(); driver.navigate().back();
請注意,以上功能完全取決于底層的瀏覽器。如果你習慣跨瀏覽器操作,當你使用這些接口時可能會出現意想不到的的異常。
?
?
7.7Cookies
// 打開Cookie作用的網站 driver.get("http://www.example.com"); // 設置全局Cookie Cookie cookie = new Cookie("key", "value"); driver.manage().addCookie(cookie); // 輸出當前網頁所有可用的Cookie Set<Cookie> allCookies = driver.manage().getCookies(); for (Cookie loadedCookie : allCookies) { System.out.println(String.format("%s -> %s", loadedCookie.getName(), loadedCookie.getValue())); } // 你又三種方法刪除Cookie // By name driver.manage().deleteCookieNamed("CookieName"); // By Cookie driver.manage().deleteCookie(loadedCookie); // Or all of them driver.manage().deleteAllCookies();
7.8 修改用戶代理服務器
FirefoxProfile profile = new FirefoxProfile(); profile.addAdditionalPreference("general.useragent.override", "some UA string"); WebDriver driver = new FirefoxDriver(profile);
7.9 拖拽Web元素
下面是一個拖拽Web頁面元素的例子,前提是本地事件必須可用。
?
WebElement element = driver.findElement(By.name("source")); WebElement target = driver.findElement(By.name("target")); (new Actions(driver)).dragAndDrop(element, target).perform();
?
?
8 各種Driver的特性以及如何選擇合適Driver
9 向前兼容:融合WebDriver和Selenium-RC
10 為遠程WebDriver單獨啟動Selenium Server
?
譯者注:
1、原文鏈接:http://www.seleniumhq.org/docs/03_webdriver.jsp。
2、文中只包含了java相關的操作,WebDriver還支持c#/Python/Ruby/Perl/PHP/Perl,如有需要,請閱讀原文。
3、language binding,又叫glue code,意思是膠水代碼,比如有個C++的lib庫,java調用這個庫的api就叫java binding。參考: http://en.wikipedia.org/wiki/Language_binding 。
4、措辭拙劣,有些單詞句子沒有深究就直譯了,深感從閱讀到翻譯差的不僅僅是一本字典,還有文化的差異。筆者強烈推薦直接閱讀官網上的原文,如果我的譯文給你造成誤解,深感不安。這也是最后三章不敢繼續班門弄斧的原因,等我對Selenium熟悉了之后再回來補全。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
