WebDriver介绍
什么是Selenium 和WebDriver?
Selenium是一個(gè)瀏覽器自動(dòng)化操作框架。Selenium主要由三種工具組成。第一個(gè)工具SeleniumIDE,是Firefox的擴(kuò)展插件,支持用戶錄制和回訪測(cè)試。錄制/回訪模式存在局限性,對(duì)許多用戶來說并不適合,因此第二個(gè)工具——Selenium WebDriver提供了各種語(yǔ)言環(huán)境的API來支持更多控制權(quán)和編寫符合標(biāo)準(zhǔn)軟件開發(fā)實(shí)踐的應(yīng)用程序。最后一個(gè)工具——SeleniumGrid幫助工程師使用Selenium API控制分布在一系列機(jī)器上的瀏覽器實(shí)例,支持并發(fā)運(yùn)行更多測(cè)試。在項(xiàng)目?jī)?nèi)部,它們分別被稱為“IDE”、“WebDriver”和“Grid”。?
這里主要介紹它的第二個(gè)工具:WebDriver。
官網(wǎng)上是這么介紹它的:WebDriver is a clean, fast framework for automated testing of webapps. 但是我覺得它并不局限與進(jìn)行自動(dòng)化測(cè)試,完全可以用作其它用途。
WebDriver針對(duì)各個(gè)瀏覽器而開發(fā),取代了嵌入到被測(cè)Web應(yīng)用中的JavaScript。與瀏覽器的緊密集成支持創(chuàng)建更高級(jí)的測(cè)試,避免了JavaScript安全模型導(dǎo)致的限制。除了來自瀏覽器廠商的支持,WebDriver還利用操作系統(tǒng)級(jí)的調(diào)用模擬用戶輸入。WebDriver支持Firefox(FirefoxDriver)、IE (InternetExplorerDriver)、Opera (OperaDriver)和Chrome (ChromeDriver)。 它還支持Android?(AndroidDriver)和iPhone (IPhoneDriver)的移動(dòng)應(yīng)用測(cè)試。它還包括一個(gè)基于HtmlUnit的無界面實(shí)現(xiàn),稱為HtmlUnitDriver。WebDriver?API可以通過Python、Ruby、Java和C#訪問,支持開發(fā)人員使用他們偏愛的編程語(yǔ)言來創(chuàng)建測(cè)試。
如何使用?(相關(guān)教程:http://www.51testing.com/zhuanti/webdriver.htm)
首先,你需要將WebDriver的JAR包加入到你項(xiàng)目中CLASSPATH中。你可以Download它通過http://code.google.com/p/selenium/downloads/list。
如果你使用的是maven構(gòu)建你的項(xiàng)目,只需要在pom.xml文件中加入下面的依賴項(xiàng)即可。
??????? <dependency>
???????????<groupId>org.seleniumhq.selenium</groupId>
???????????<artifactId>selenium-java</artifactId>
?????? ?????<version>2.25.0</version>
??????? </dependency>
??????? <dependency>
???????????<groupId>org.seleniumhq.selenium</groupId>
???????????<artifactId>selenium-server</artifactId>
???????????<version>2.25.0</version>
??????? </dependency>
然后,你就可以使用它了。WebDriver的API遵從”Best Fit”原則,在保持良好的用戶體驗(yàn)性和靈活性之間找到一個(gè)最佳的平衡點(diǎn)。
下面的例子是使用HtmlUnitDriver。HtmlUnitDriver只會(huì)在內(nèi)存中執(zhí)行這段代碼,不會(huì)彈出一個(gè)真實(shí)的頁(yè)面。
packageorg.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example ?{
? ? public static void main(String[] args) {
? ? ? ? // Create a new instance of the html unit driver
? ? ? ? // Notice that the remainder of the code relies onthe interface,?
? ? ? ? // not the implementation.
? ? ? ? WebDriver driver = new HtmlUnitDriver();
? ? ? ? // And now use this to visit Google
? ? ? ? driver.get("http://www.google.com");
? ? ? ? // Find the text input element by its name
? ? ? ? WebElement element = driver.findElement(By.name("q"));
? ? ? ? // Enter something to search for
? ? ? ? element.sendKeys("Cheese!");
? ? ? ? // Now submit the form. WebDriver will find theform for us from the element
? ? ? ? element.submit();
? ? ? ? // Check the title of the page
? ? ? ? System.out.println("Page title is: " +driver.getTitle());
? ? }
}
如果你想使用Firefox瀏覽器。你只需要將WebDriver driver = new FirefoxDriver()。前提是你的Firefox被安裝在默認(rèn)的位置。
| 操作系統(tǒng) | Firefox默認(rèn)安裝位置 |
| Linux | firefox (found using "which") |
| Mac | /Applications/Firefox.app/Contents/MacOS/firefox |
| Windows | %PROGRAMFILES%\Mozilla Firefox\firefox.exe |
如果你的FireFox沒有被安裝在指定的位置,你可以設(shè)置“webdriver.firefox.bin”
環(huán)境變量的值來指定它的位置。在Java中可以使用如下代碼:
System.setProperty("webdriver.firefox.bin","thelocation of Firefox");
如果要使用Chrome瀏覽器的話相對(duì)麻煩些。你需要首先下載一個(gè)ChromeDriver(下載地址:http://code.google.com/p/chromedriver/downloads/list)。這個(gè)程序是由Chrome團(tuán)隊(duì)提供的,你可以看做它是鏈接WebDriver和Chrome瀏覽器的橋梁。然后啟動(dòng)ChromeDriver,你會(huì)得到一個(gè)Url及監(jiān)聽端口。然后使用webDriver = newRemoteWebDriver(url, DesiredCapabilities.chrome())創(chuàng)建一個(gè)ChromeWebDriver進(jìn)行操作。當(dāng)然你可以在一個(gè)子線程中啟動(dòng)ChromeDriver,并設(shè)置給WebDriver。
??????? File file = new File(your chromedriverfile path);
?? ChromeDriverService service = newChromeDriverService.Builder().usingChromeDriverExecutable(file).usingAnyFreePort().build();
??????? service.start();
WebDriver? webDriver = new ChromeDriver(service);
…..
…..
….
? service.stop();
WebDriver如何工作
WebDriver是W3C的一個(gè)標(biāo)準(zhǔn),由Selenium主持。
具體的協(xié)議標(biāo)準(zhǔn)可以從http://code.google.com/p/selenium/wiki/JsonWireProtocol#Command_Reference?? 查看。
從這個(gè)協(xié)議中我們可以看到,WebDriver之所以能夠?qū)崿F(xiàn)與瀏覽器進(jìn)行交互,是因?yàn)闉g覽器實(shí)現(xiàn)了這些協(xié)議。這個(gè)協(xié)議是使用JOSN通過HTTP進(jìn)行傳輸。
它的實(shí)現(xiàn)使用了經(jīng)典的Client-Server模式。客戶端發(fā)送一個(gè)requset,服務(wù)器端返回一個(gè)response。
我們明確幾個(gè)概念。
Client
調(diào)用?WebDriverAPI的機(jī)器。
Server
運(yùn)行瀏覽器的機(jī)器。Firefox瀏覽器直接實(shí)現(xiàn)了WebDriver的通訊協(xié)議,而Chrome和IE則是通過ChromeDriver和InternetExplorerDriver實(shí)現(xiàn)的。
Session
服務(wù)器端需要維護(hù)瀏覽器的Session,從客戶端發(fā)過來的請(qǐng)求頭中包含了Session信息,服務(wù)器端將會(huì)執(zhí)行對(duì)應(yīng)的瀏覽器頁(yè)面。
WebElement
這是WebDriverAPI中的對(duì)象,代表頁(yè)面上的一個(gè)DOM元素。
舉個(gè)實(shí)際的例子,下面代碼的作用是”命令”firefox轉(zhuǎn)跳到google主頁(yè):
?? ? ? WebDriver driver = new FirefoxDriver();
??????? //實(shí)例化一個(gè)Driver
? ? ? ? driver.get("http://www.google.com");
在執(zhí)行driver.get("http://www.google.com")這句代碼時(shí),client,也就是我們的測(cè)試代碼向remote server發(fā)送了如下的請(qǐng)求:
POSTsession/285b12e4-2b8a-4fe6-90e1-c35cba245956/url? post_data{"url":"http://google.com"}??
通過post的方式請(qǐng)求localhost:port/hub/session/session_id/url地址,請(qǐng)求瀏覽器完成跳轉(zhuǎn)url的操作。
如果上述請(qǐng)求是可接受的,或者說remote server是實(shí)現(xiàn)了這個(gè)接口,那么remote server會(huì)跳轉(zhuǎn)到該post data包含的url,并返回如下的response
{"name":"get","sessionId":"285b12e4-2b8a-4fe6-90e1-c35cba245956","status":0,"value":""}?
該response中包含如下信息
name:remote server端的實(shí)現(xiàn)的方法的名稱,這里是get,表示跳轉(zhuǎn)到指定url;
sessionId:當(dāng)前session的id;
status:請(qǐng)求執(zhí)行的狀態(tài)碼,非0表示未正確執(zhí)行,這里是0,表示一切ok不許擔(dān)心;
value:請(qǐng)求的返回值,這里返回值為空,如果client調(diào)用title接口,則該值應(yīng)該是當(dāng)前頁(yè)面的title;
如果client發(fā)送的請(qǐng)求是定位某個(gè)特定的頁(yè)面元素,則response的返回值可能是這樣的:
{"name":"findElement","sessionId":"285b12e4-2b8a-4fe6-90e1-c35cba245956","status":0,"value":{"ELEMENT":"{2192893e-f260-44c4-bdf6-7aad3c919739}"}}?
name,sessionId,status跟上面的例子是差不多的,區(qū)別是該請(qǐng)求的返回值是ELEMENT:{2192893e-f260-44c4-bdf6-7aad3c919739},表示定位到元素的id,通過該id,client可以發(fā)送如click之類的請(qǐng)求與 server端進(jìn)行交互。
如何用webdriver打開一個(gè)瀏覽器,我們常用的瀏覽器有firefox和IE兩種,firefox是selenium支持得比較成熟的瀏覽器,很多新的特性都會(huì)在firefox中體現(xiàn)。但是做頁(yè)面的測(cè)試,啟動(dòng)速度比較慢,啟動(dòng)以后運(yùn)行速度還是可以接受的。
啟動(dòng)firefox瀏覽器
新建一個(gè)firefoxDriver
如果火狐瀏覽器沒有默認(rèn)安裝在C盤,需要制定其路徑
啟動(dòng)IE瀏覽器
//Create a newinstance of the Internet Explorer driver
WebDriver driver = newInternetExplorerDriver ();
啟動(dòng)HtmlUnit瀏覽器
//Createa new instance of the HtmlUnit?driver
WebDriverdriver = new HtmlUnitDriver();
啟動(dòng)Chrome瀏覽器
下載ChromeDriver.exe請(qǐng)點(diǎn)?這里//Createa new instance of the Chromedriver
System.setProperty(“webdriver.chrome.driver”, bsPath);
WebDriverdriver = new ChromeDriver();
對(duì)web頁(yè)面進(jìn)行測(cè)試,首先要打開被測(cè)試頁(yè)面的地址(如:http://www.baidu.com),web driver 提供的get方法可以打開一個(gè)頁(yè)面:
// And now use thedriver to visit Google
driver.get(“http://www.baidu.com“);
//也可以調(diào)用以下方法
driver.navigate().to(“http://www.baidu.com“);
測(cè)試腳本如下
package com.test.ui.demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestWebDriver {undefined
private WebDriver driver = null;
private String url = “http://www.baidu.com“;
//每個(gè)用例執(zhí)行前會(huì)執(zhí)行該方法
@BeforeMethod
public void startUp(){undefined
//如果firefox沒有安裝在c盤需要執(zhí)行下面這句,否則請(qǐng)注釋掉
System.setProperty(“webdriver.firefox.bin”, “D:/Program Files/Mozilla firefox/firefox.exe”);
driver = new FirefoxDriver();
}
//每個(gè)用例執(zhí)行后會(huì)執(zhí)行該方法
@AfterMethod
public void tearDown(){undefined
//退出操作
driver.quit();
driver = null;
}
@Test
public void startTest(){undefined
//打開新窗口
driver.get(url);
}
}
各種瀏覽器比較↓
Webdirver對(duì)瀏覽器的支持HtmlUnit Driver優(yōu)點(diǎn):HtmlUnit Driver不會(huì)實(shí)際打開瀏覽器,運(yùn)行速度很快。對(duì)于用FireFox等瀏覽器來做測(cè)試的自動(dòng)化測(cè)試用例,運(yùn)行速度通常很慢,HtmlUnit Driver無疑是可以很好地解決這個(gè)問題。
缺點(diǎn):它對(duì)JavaScript的支持不夠好,當(dāng)頁(yè)面上有復(fù)雜JavaScript時(shí),經(jīng)常會(huì)捕獲不到頁(yè)面元素。
使用:
WebDriver driver = new HtmlUnitDriver();
FireFox Driver優(yōu)點(diǎn):FireFox Dirver對(duì)頁(yè)面的自動(dòng)化測(cè)試支持得比較好,很直觀地模擬頁(yè)面的操作,對(duì)JavaScript的支持也非常完善,基本上頁(yè)面上做的所有操作FireFox Driver都可以模擬。
缺點(diǎn):啟動(dòng)很慢,運(yùn)行也比較慢,不過,啟動(dòng)之后Webdriver的操作速度雖然不快但還是可以接受的,建議不要頻繁啟停FireFox Driver。
使用:
WebDriver driver = new FirefoxDriver();
Firefox profile的屬性值是可以改變的,比如我們平時(shí)可能需要通過代理上網(wǎng),可以這樣修改:
FirefoxProfile profile = new FirefoxProfile();
//使用profile
??? ProfilesIni allProfiles = new ProfilesIni();
??? FirefoxProfile profile = allProfiles.getProfile("default");
??? driver = new FirefoxDriver(profile);
// 使用代理
profile.setPreference(“network.proxy.type”,?1);
// http協(xié)議代理配置
profile.setPreference(“network.proxy.http”, proxyIp);
profile.setPreference(“network.proxy.http_port”, proxyPort);
// 所有協(xié)議公用一種代理配置,如果單獨(dú)配置,這項(xiàng)設(shè)置為false,再類似于http的配置
profile.setPreference(“network.proxy.share_proxy_settings”, true);
// 對(duì)于localhost的不用代理,這里必須要配置,否則無法和webdriver通訊
profile.setPreference(“network.proxy.no_proxies_on”, “l(fā)ocalhost”);
// 以代理方式啟動(dòng)firefox
FirefoxDriver ff??= new FirefoxDriver(profile);
InternetExplorer Driver優(yōu)點(diǎn):直觀地模擬用戶的實(shí)際操作,對(duì)JavaScript提供完善的支持。
缺點(diǎn):是所有瀏覽器中運(yùn)行速度最慢的,并且只能在Windows下運(yùn)行,對(duì)CSS以及XPATH的支持也不夠好。
使用:
WebDriver driver = new InternetExplorerDriver();
元素操作↓
查找元素
使用操作如何找到頁(yè)面元素Webdriver的findElement方法可以用來找到頁(yè)面的某個(gè)元素,最常用的方法是用id和name查找。下面介紹幾種比較常用的方法。
By ID假設(shè)頁(yè)面寫成這樣:
<input type=”text” name=”userName” ?id=”user” />
那么可以這樣找到頁(yè)面的元素:
通過id查找:
WebElement element = driver.findElement(By.id(“user”));
By Name或通過name查找:
WebElement element = driver.findElement(By.name(“userName”));
By XPATH或通過xpath查找:
WebElement element =driver.findElement(By.xpath(“//input[@id='user']“));
By Class Name假設(shè)頁(yè)面寫成這樣:
<div class=”top”><span>Head</span></div><divclass=”top”><span>HeadName</span></div>
可以通過這樣查找頁(yè)面元素:
List<WebElement>top= driver.findElements(By.className(“top”));
By Link Text假設(shè)頁(yè)面元素寫成這樣:
<a href=”http://www.baidu.com”>baidu</a>>
那么可以通過這樣查找:
WebElement baidu=driver.findElement(By.linkText(“baidu”));
輸入框傳值
輸入框(text field or textarea)? ?找到輸入框元素:
WebElement element = driver.findElement(By.id(“passwd-id”));
在輸入框中輸入內(nèi)容:
element.sendKeys(“test”);
將輸入框清空:
element.clear();
獲取輸入框的文本內(nèi)容:
element.getText();
下拉菜單
下拉選擇框(Select)找到下拉選擇框的元素:
Select select = new Select(driver.findElement(By.id(“select”)));
選擇對(duì)應(yīng)的選擇項(xiàng):select.selectByVisibleText(“testName”);
或
select.selectByValue(“name”);
不選擇對(duì)應(yīng)的選擇項(xiàng):
select.deselectAll();
select.deselectByValue(“name”);
select.deselectByVisibleText(“姓名”);
或者獲取選擇項(xiàng)的值:
select.getAllSelectedOptions();
select.getFirstSelectedOption();
單選框
單選項(xiàng)(Radio Button)找到單選框元素:
WebElement sex=driver.findElement(By.id(“sex”));
選擇某個(gè)單選項(xiàng):
sex.click();
清空某個(gè)單選項(xiàng):
sex.clear();
判斷某個(gè)單選項(xiàng)是否已經(jīng)被選擇:
sex.isSelected();
復(fù)選框
多選項(xiàng)(checkbox)多選項(xiàng)的操作和單選的差不多:
WebElement area =driver.findElement(By.id(“area?.”));
area?.click();
area?.clear();
area?.isSelected();
area?.isEnabled();
按鈕
按鈕(button)找到按鈕元素:
WebElement saveButton = driver.findElement(By.id(“save”));
點(diǎn)擊按鈕:
saveButton.click();
判斷按鈕是否enable:
saveButton.isEnabled ();
左右選擇框也就是左邊是可供選擇項(xiàng),選擇后移動(dòng)到右邊的框中,反之亦然。例如:
Select name= new Select(driver.findElement(By.id(“name”)));
name.selectByVisibleText(“hellen”);
WebElement addName=driver.findElement(By.id(“addButton”));
addName.click();
彈出框
彈出對(duì)話框(Popup dialogs)Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.getText();
表單提交
表單(Form)Form中的元素的操作和其它的元素操作一樣,對(duì)元素操作完成后對(duì)表單的提交可以:
WebElement sub= driver.findElement(By.id(“sub”));
sub.click();
或
sub.submit();//只適合于表單的提交
上傳附件
上傳文件 (Upload File)上傳文件的元素操作:
WebElement picFile = driver.findElement(By.id(“picFile?”));
String filePath = “d:\\report\\600x600x0.jpg”;
picFile?.sendKeys(filePath);
多窗口切換
Windows 或 Frames之間的切換
首先切換到默認(rèn)的frame
driver.switchTo().defaultContent();
切換到某個(gè)frame:
driver.switchTo().frame(“l(fā)eftFrame”);
從一個(gè)frame切換到另一個(gè)frame:
driver.switchTo().frame(“mainFrame”);
切換到某個(gè)window:
driver.switchTo().window(“windowName”);
導(dǎo)航
導(dǎo)航 (Navigationand History)打開一個(gè)新的頁(yè)面:
driver.navigate().to(“http://www.baidu.com”);
通過歷史導(dǎo)航返回原頁(yè)面:
driver.navigate().forward();
driver.navigate().back();
以上為簡(jiǎn)單介紹了一下webDriver中常遇到的操作,有問題可以查閱官方的API文檔
總結(jié)
以上是生活随笔為你收集整理的WebDriver介绍的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 赵克明医生(赵克明)
- 下一篇: 如何使用selenium webdriv