WebDriver介紹

麼是Selenium 和WebDriver?

Selenium是一個瀏覽器自動化操作框架。Selenium主要由三種工具組成。第一個工具SeleniumIDE,是Firefox的擴展插件,支持用戶錄製和回訪測試。錄製/回訪模式存在侷限性,對許多用戶來說並不適合,因此第二個工具——Selenium WebDriver提供了各種語言環境的API來支持更多控制權和編寫符合標準軟件開發實踐的應用程序。最後一個工具——SeleniumGrid幫助工程師使用Selenium API控制分佈在一系列機器上的瀏覽器實例,支持併發運行更多測試。在項目內部,它們分別被稱爲“IDE”、“WebDriver”和“Grid”。 

這裏主要介紹它的第二個工具:WebDriver。

官網上是這麼介紹它的:WebDriver is a clean, fast framework for automated testing of webapps. 但是我覺得它並不侷限與進行自動化測試,完全可以用作其它用途。

WebDriver針對各個瀏覽器而開發,取代了嵌入到被測Web應用中的JavaScript。與瀏覽器的緊密集成支持創建更高級的測試,避免了JavaScript安全模型導致的限制。除了來自瀏覽器廠商的支持,WebDriver還利用操作系統級的調用模擬用戶輸入。WebDriver支持Firefox(FirefoxDriver)、IE (InternetExplorerDriver)、Opera (OperaDriver)和Chrome (ChromeDriver)。 它還支持Android (AndroidDriver)和iPhone (IPhoneDriver)的移動應用測試。它還包括一個基於HtmlUnit的無界面實現,稱爲HtmlUnitDriver。WebDriver API可以通過Python、Ruby、Java和C#訪問,支持開發人員使用他們偏愛的編程語言來創建測試。

 

何使用?(相關教程:http://www.51testing.com/zhuanti/webdriver.htm)

首先,你需要將WebDriver的JAR包加入到你項目中CLASSPATH中。你可以Download它通過http://code.google.com/p/selenium/downloads/list

如果你使用的是maven構建你的項目,只需要在pom.xml文件中加入下面的依賴項即可。

        <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”原則,在保持良好的用戶體驗性和靈活性之間找到一個最佳的平衡點。

下面的例子是使用HtmlUnitDriver。HtmlUnitDriver只會在內存中執行這段代碼,不會彈出一個真實的頁面。

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被安裝在默認的位置。

操作系統

Firefox默認安裝位置

Linux

firefox (found using "which")

Mac

/Applications/Firefox.app/Contents/MacOS/firefox

Windows

%PROGRAMFILES%\Mozilla Firefox\firefox.exe

如果你的FireFox沒有被安裝在指定的位置,你可以設置“webdriver.firefox.bin”

環境變量的值來指定它的位置。在Java中可以使用如下代碼:

System.setProperty("webdriver.firefox.bin","thelocation of Firefox");

如果要使用Chrome瀏覽器的話相對麻煩些。你需要首先下載一個ChromeDriver(下載地址:http://code.google.com/p/chromedriver/downloads/list)。這個程序是由Chrome團隊提供的,你可以看做它是鏈接WebDriver和Chrome瀏覽器的橋樑。然後啓動ChromeDriver,你會得到一個Url及監聽端口。然後使用webDriver = newRemoteWebDriver(url, DesiredCapabilities.chrome())創建一個ChromeWebDriver進行操作。當然你可以在一個子線程中啓動ChromeDriver,並設置給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的一個標準,由Selenium主持。

具體的協議標準可以從http://code.google.com/p/selenium/wiki/JsonWireProtocol#Command_Reference   查看。

從這個協議中我們可以看到,WebDriver之所以能夠實現與瀏覽器進行交互,是因爲瀏覽器實現了這些協議。這個協議是使用JOSN通過HTTP進行傳輸。

它的實現使用了經典的Client-Server模式。客戶端發送一個requset,服務器端返回一個response。

我們明確幾個概念。

Client

調用 WebDriverAPI的機器。

Server

運行瀏覽器的機器。Firefox瀏覽器直接實現了WebDriver的通訊協議,而Chrome和IE則是通過ChromeDriver和InternetExplorerDriver實現的。

Session

服務器端需要維護瀏覽器的Session,從客戶端發過來的請求頭中包含了Session信息,服務器端將會執行對應的瀏覽器頁面。

WebElement

這是WebDriverAPI中的對象,代表頁面上的一個DOM元素。

舉個實際的例子,下面代碼的作用是”命令”firefox轉跳到google主頁:

 

       WebDriver driver = new FirefoxDriver();
        //實例化一個
Driver
 
        driver.get("http://www.google.com");

 

在執行driver.get("http://www.google.com")這句代碼時,client,也就是我們的測試代碼向remote server發送瞭如下的請求:

POSTsession/285b12e4-2b8a-4fe6-90e1-c35cba245956/url  post_data{"url":"http://google.com"}  

通過post的方式請求localhost:port/hub/session/session_id/url地址,請求瀏覽器完成跳轉url的操作。

如果上述請求是可接受的,或者說remote server是實現了這個接口,那麼remote server會跳轉到該post data包含的url,並返回如下的response

{"name":"get","sessionId":"285b12e4-2b8a-4fe6-90e1-c35cba245956","status":0,"value":""} 

response中包含如下信息

name:remote server端的實現的方法的名稱,這裏是get,表示跳轉到指定url;

sessionId:當前session的id;

status:請求執行的狀態碼,非0表示未正確執行,這裏是0,表示一切ok不許擔心;

value:請求的返回值,這裏返回值爲空,如果client調用title接口,則該值應該是當前頁面的title;

如果client發送的請求是定位某個特定的頁面元素,則response的返回值可能是這樣的:

{"name":"findElement","sessionId":"285b12e4-2b8a-4fe6-90e1-c35cba245956","status":0,"value":{"ELEMENT":"{2192893e-f260-44c4-bdf6-7aad3c919739}"}} 

name,sessionId,status跟上面的例子是差不多的,區別是該請求的返回值是ELEMENT:{2192893e-f260-44c4-bdf6-7aad3c919739},表示定位到元素的id,通過該id,client可以發送如click之類的請求與 server端進行交互。



何用webdriver打開一個瀏覽器,我們常用的瀏覽器有firefox和IE兩種,firefox是selenium支持得比較成熟的瀏覽器,很多新的特性都會在firefox中體現。但是做頁面的測試,啓動速度比較慢,啓動以後運行速度還是可以接受的。

啓動firefox瀏覽器

新建一個firefoxDriver
如果火狐瀏覽器沒有默認安裝在C盤,需要制定其路徑

System.setProperty("webdriver.firefox.bin", "D:/Program Files/Mozilla firefox/firefox.exe"); 
WebDriver driver = newFirefoxDriver(); 

啓動IE瀏覽器

//Create a newinstance of the Internet Explorer driver
WebDriver driver = newInternetExplorerDriver ();

啓動HtmlUnit瀏覽器

//Createa new instance of the HtmlUnit driver
WebDriverdriver = new HtmlUnitDriver();

啓動Chrome瀏覽器

          下載ChromeDriver.exe請點這裏

//Createa new instance of the Chromedriver

System.setProperty(“webdriver.chrome.driver”, bsPath);
WebDriverdriver = new ChromeDriver();

對web頁面進行測試,首先要打開被測試頁面的地址(如:http://www.baidu.com),web driver 提供的get方法可以打開一個頁面:
// And now use thedriver to visit Google
driver.get(“http://www.baidu.com“);
//也可以調用以下方法
driver.navigate().to(“http://www.baidu.com“);
測試腳本如下
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 {
private WebDriver driver = null;
private String url = “http://www.baidu.com“;
//每個用例執行前會執行該方法
@BeforeMethod
public void startUp(){
//如果firefox沒有安裝在c盤需要執行下面這句,否則請註釋掉
System.setProperty(“webdriver.firefox.bin”, “D:/Program Files/Mozilla firefox/firefox.exe”);
driver = new FirefoxDriver();
}
//每個用例執行後會執行該方法
@AfterMethod
public void tearDown(){
//退出操作
driver.quit();
driver = null;
}
@Test
public void startTest(){
//打開新窗口
driver.get(url);
}
}

各種瀏覽器比較↓

Webdirver對瀏覽器的支持HtmlUnit Driver優點:HtmlUnit Driver不會實際打開瀏覽器,運行速度很快。對於用FireFox等瀏覽器來做測試的自動化測試用例,運行速度通常很慢,HtmlUnit Driver無疑是可以很好地解決這個問題。
缺點:它對JavaScript的支持不夠好,當頁面上有複雜JavaScript時,經常會捕獲不到頁面元素。
使用:
WebDriver driver = new HtmlUnitDriver();

FireFox Driver優點:FireFox Dirver對頁面的自動化測試支持得比較好,很直觀地模擬頁面的操作,對JavaScript的支持也非常完善,基本上頁面上做的所有操作FireFox Driver都可以模擬。
缺點:啓動很慢,運行也比較慢,不過,啓動之後Webdriver的操作速度雖然不快但還是可以接受的,建議不要頻繁啓停FireFox Driver。
使用:
WebDriver driver = new FirefoxDriver();
Firefox profile的屬性值是可以改變的,比如我們平時可能需要通過代理上網,可以這樣修改:
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協議代理配置

profile.setPreference(“network.proxy.http”, proxyIp);
profile.setPreference(“network.proxy.http_port”, proxyPort);

// 所有協議公用一種代理配置,如果單獨配置,這項設置爲false,再類似於http的配置

profile.setPreference(“network.proxy.share_proxy_settings”, true);

// 對於localhost的不用代理,這裏必須要配置,否則無法和webdriver通訊

profile.setPreference(“network.proxy.no_proxies_on”, “localhost”);

// 以代理方式啓動firefox

FirefoxDriver ff  = new FirefoxDriver(profile);

InternetExplorer Driver優點:直觀地模擬用戶的實際操作,對JavaScript提供完善的支持。
缺點:是所有瀏覽器中運行速度最慢的,並且只能在Windows下運行,對CSS以及XPATH的支持也不夠好。
使用:
WebDriver driver = new InternetExplorerDriver();

元素操作↓

查找元素

使用操作如何找到頁面元素Webdriver的findElement方法可以用來找到頁面的某個元素,最常用的方法是用id和name查找。下面介紹幾種比較常用的方法。
By ID假設頁面寫成這樣:
< input type=”text” name=”userName”  id=”user” />
那麼可以這樣找到頁面的元素:
通過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假設頁面寫成這樣:

<div class=”top”><span>Head</span></div><divclass=”top”><span>HeadName</span></div>
可以通過這樣查找頁面元素:
List<WebElement>top= driver.findElements(By.className(“top”));

By Link Text假設頁面元素寫成這樣:
< 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”));
在輸入框中輸入內容:
element.sendKeys(“test”);
將輸入框清空:
element.clear();
獲取輸入框的文本內容:
element.getText();

下拉菜單

下拉選擇框(Select)找到下拉選擇框的元素:
Select select = new Select(driver.findElement(By.id(“select”)));
選擇對應的選擇項:select.selectByVisibleText(“testName”);

select.selectByValue(“name”);
不選擇對應的選擇項:
select.deselectAll();
select.deselectByValue(“name”);
select.deselectByVisibleText(“姓名”);
或者獲取選擇項的值:
select.getAllSelectedOptions();
select.getFirstSelectedOption();

單選框

單選項(Radio Button)找到單選框元素:
WebElement sex=driver.findElement(By.id(“sex”));

選擇某個單選項:

sex.click();
清空某個單選項:
sex.clear();

判斷某個單選項是否已經被選擇:

sex.isSelected();

複選框

多選項(checkbox)多選項的操作和單選的差不多:
WebElement area =driver.findElement(By.id(“area .”));
area .click();
area .clear();
area .isSelected();
area .isEnabled();

按鈕

按鈕(button)找到按鈕元素:
WebElement saveButton = driver.findElement(By.id(“save”));

點擊按鈕:

saveButton.click();

判斷按鈕是否enable:

saveButton.isEnabled ();

左右選擇框也就是左邊是可供選擇項,選擇後移動到右邊的框中,反之亦然。例如:

Select name= new Select(driver.findElement(By.id(“name”)));
name.selectByVisibleText(“hellen”);
WebElement addName=driver.findElement(By.id(“addButton”));
addName.click();

彈出框

彈出對話框(Popup dialogs)Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.getText();

表單提交

表單(Form)Form中的元素的操作和其它的元素操作一樣,對元素操作完成後對錶單的提交可以:
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之間的切換

首先切換到默認的frame
driver.switchTo().defaultContent();
切換到某個frame:
driver.switchTo().frame(“leftFrame”);
從一個frame切換到另一個frame:
driver.switchTo().frame(“mainFrame”);
切換到某個window:
driver.switchTo().window(“windowName”);

導航

導航 (Navigationand History)打開一個新的頁面:
driver.navigate().to(“http://www.baidu.com”);

通過歷史導航返回原頁面:
driver.navigate().forward();
driver.navigate().back();

以上爲簡單介紹了一下webDriver中常遇到的操作,有問題可以查閱官方的API文檔


轉載自https://blog.csdn.net/scratlc/article/details/62044040
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章