1. 程式人生 > >webdriver API中文版詳細介紹

webdriver API中文版詳細介紹

說明:

WebDriver與之前Selenium的JS注入實現不同,直接利用了瀏覽器native support來操作瀏覽器。所以對於不同平臺,不同的瀏覽器,必須依賴一個特定的瀏覽器的native component來實現把WebDriver API的呼叫轉化為瀏覽器的native invoke。

在我們new一個WebDriver的過程中,Selenium首先會確認瀏覽器的native component是否存在可用而且版本匹配。接著就在目標瀏覽器裡啟動一整套Web Service,這套Web Service使用了Selenium自己設計定義的協議,名字叫做The WebDriver Wire Protocol

。這套協議非常之強大,幾乎可以操作瀏覽器做任何事情,包括開啟、關閉、最大化、最小化、元素定位、元素點選、上傳檔案等等等等。

1.1   下載selenium2.0的lib包

1.2   用webdriver開啟一個瀏覽器

我們常用的瀏覽器有firefox和IE兩種,firefox是selenium支援得比較成熟的瀏覽器。但是做頁面的測試,速度通常很慢,嚴重影響持續整合的速度,這個時候建議使用HtmlUnit,不過HtmlUnitDirver執行時是看不到介面的,對除錯就不方便了。使用哪種瀏覽器,可以做成配置項,根據需要靈活配置。

  1. 開啟firefox瀏覽器:

        //Create a newinstance of the Firefox driver

        WebDriver driver = newFirefoxDriver();

  1. 開啟IE瀏覽器

        //Create a newinstance of the Internet Explorer driver

        WebDriver driver = newInternetExplorerDriver ();

  1. 開啟HtmlUnit瀏覽器

        //Createa new instance of the Internet Explorer driver    

        WebDriverdriver = new HtmlUnitDriver();

1.3   開啟測試頁面

對頁面對測試,首先要開啟被測試頁面的地址(如:http://www.google.com),web driver 提供的get方法可以開啟一個頁面:

        // And now use thedriver to visit Google

        driver.get("http://www.google.com");

1.4   GettingStarted

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 voidmain(String[] args) {

        // Create a newinstance of the Firefox driver

        // Notice that theremainder of the code relies on the interface,

        // not the implementation.

        WebDriver driver = newFirefoxDriver();

        // And now use this tovisit Google

       driver.get("http://www.google.com");

        // Alternatively thesame thing can be done like this

        // driver.navigate().to("http://www.google.com");

        // Find the text inputelement by its name

        WebElement element =driver.findElement(By.name("q"));

        // Enter something tosearch for

       element.sendKeys("Cheese!");

        // Now submit the form.WebDriver will find the form for us from the element

        element.submit();

        // Check the title ofthe page

       System.out.println("Page title is: " + driver.getTitle());

        // Google's search isrendered dynamically with JavaScript.

        // Wait for the pageto load, timeout after 10 seconds

        (newWebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {

         public Booleanapply(WebDriver d) {

                returnd.getTitle().toLowerCase().startsWith("cheese!");

            }

        });

        // Should see:"cheese! - Google Search"

       System.out.println("Page title is: " + driver.getTitle());

        //Close the browser

        driver.quit();

    }

}

第2章        Webdirver對瀏覽器的支援

2.1   HtmlUnit Driver

優點:HtmlUnit Driver不會實際開啟瀏覽器,執行速度很快。對於用FireFox等瀏覽器來做測試的自動化測試用例,執行速度通常很慢,HtmlUnit Driver無疑是可以很好地解決這個問題。

缺點:它對JavaScript的支援不夠好,當頁面上有複雜JavaScript時,經常會捕獲不到頁面元素。

使用:

WebDriver driver = new HtmlUnitDriver();

2.2   FireFox Driver

優點:FireFox Dirver對頁面的自動化測試支援得比較好,很直觀地模擬頁面的操作,對JavaScript的支援也非常完善,基本上頁面上做的所有操作FireFox Driver都可以模擬。

缺點:啟動很慢,執行也比較慢,不過,啟動之後Webdriver的操作速度雖然不快但還是可以接受的,建議不要頻繁啟停FireFox Driver。

使用:

WebDriver driver = new FirefoxDriver();

Firefox profile的屬性值是可以改變的,比如我們平時使用得非常頻繁的改變useragent的功能,可以這樣修改:

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "some UAstring");
WebDriver driver = new FirefoxDriver(profile);

2.3   InternetExplorer Driver

優點:直觀地模擬使用者的實際操作,對JavaScript提供完善的支援。

缺點:是所有瀏覽器中執行速度最慢的,並且只能在Windows下執行,對CSS以及XPATH的支援也不夠好。

使用:

WebDriver driver = new InternetExplorerDriver();

第3章        使用操作

3.1  如何找到頁面元素

Webdriver的findElement方法可以用來找到頁面的某個元素,最常用的方法是用id和name查詢。下面介紹幾種比較常用的方法。

3.1.1 By ID

假設頁面寫成這樣:

<input type="text" name="passwd"id="passwd-id" />

那麼可以這樣找到頁面的元素:

通過id查詢:

WebElement element = driver.findElement(By.id("passwd-id"));

3.1.2 By Name

或通過name查詢:

WebElement element = driver.findElement(By.name("passwd"));

3.1.3 By XPATH

或通過xpath查詢:

WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']"));

3.1.4 By Class Name

假設頁面寫成這樣:

<div class="cheese"><span>Cheddar</span></div><divclass="cheese"><span>Gouda</span></div>

可以通過這樣查詢頁面元素:

List<WebElement>cheeses = driver.findElements(By.className("cheese"));

3.1.5 By Link Text

假設頁面元素寫成這樣:

<ahref="http://www.google.com/search?q=cheese">cheese</a>>

 那麼可以通過這樣查詢:

WebElement cheese =driver.findElement(By.linkText("cheese"));

3.2  如何對頁面元素進行操作

找到頁面元素後,怎樣對頁面進行操作呢?我們可以根據不同的型別的元素來進行一一說明。

3.2.1 輸入框(text field or textarea)

   找到輸入框元素:

WebElement element = driver.findElement(By.id("passwd-id"));

在輸入框中輸入內容:

element.sendKeys(“test”);

將輸入框清空:

element.clear();

獲取輸入框的文字內容:

element.getText();

3.2.2 下拉選擇框(Select)

找到下拉選擇框的元素:

Select select = new Select(driver.findElement(By.id("select")));

  選擇對應的選擇項:

select.selectByVisibleText(“mediaAgencyA”);

select.selectByValue(“MA_ID_001”);

不選擇對應的選擇項:

select.deselectAll();

select.deselectByValue(“MA_ID_001”);

select.deselectByVisibleText(“mediaAgencyA”);

或者獲取選擇項的值:

select.getAllSelectedOptions();

select.getFirstSelectedOption();

3.2.3 單選項(Radio Button)

找到單選框元素:

WebElement bookMode =driver.findElement(By.id("BookMode"));

選擇某個單選項:

bookMode.click();

清空某個單選項:

bookMode.clear();

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

bookMode.isSelected();

3.2.4 多選項(checkbox)

多選項的操作和單選的差不多:

WebElement checkbox =driver.findElement(By.id("myCheckbox."));

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

3.2.5 按鈕(button)

找到按鈕元素:

WebElement saveButton = driver.findElement(By.id("save"));

點選按鈕:

saveButton.click();

判斷按鈕是否enable:

saveButton.isEnabled ();

3.2.6 左右選擇框

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

Select lang = new Select(driver.findElement(By.id("languages")));

lang.selectByVisibleText(“English”);

WebElement addLanguage =driver.findElement(By.id("addButton"));

addLanguage.click();

3.2.7 彈出對話方塊(Popup dialogs)

Alert alert = driver.switchTo().alert();

alert.accept();

alert.dismiss();

alert.getText();

3.2.8 表單(Form)

Form中的元素的操作和其它的元素操作一樣,對元素操作完成後對錶單的提交可以:

WebElement approve = driver.findElement(By.id("approve"));

approve.click();

approve.submit();//只適合於表單的提交

3.2.9 上傳檔案 (Upload File)

上傳檔案的元素操作:

WebElement adFileUpload = driver.findElement(By.id("WAP-upload"));

String filePath = "C:\test\\uploadfile\\media_ads\\test.jpg";

adFileUpload.sendKeys(filePath);

3.2.10                 Windows 和 Frames之間的切換

一般來說,登入後建議是先:

driver.switchTo().defaultContent();

切換到某個frame:

driver.switchTo().frame("leftFrame");

從一個frame切換到另一個frame:

driver.switchTo().frame("mainFrame");

切換到某個window:

driver.switchTo().window("windowName");

3.2.11                 拖拉(Drag andDrop)

WebElement element =driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element, target).perform();

3.2.12                 導航 (Navigationand History)

開啟一個新的頁面:

 driver.navigate().to("http://www.example.com");

通過歷史導航返回原頁面:

driver.navigate().forward();

driver.navigate().back();

3.3   高階使用

3.3.1 改變user agent

User Agent的設定是平時使用得比較多的操作:

FirefoxProfile profile = new FirefoxProfile();

profile.addAdditionalPreference("general.useragent.override","some UA string");

WebDriver driver = new FirefoxDriver(profile);

3.3.2 讀取Cookies

我們經常要對的值進行讀取和設定。

增加cookie:

// Now set the cookie. This one's valid for the entire domain

Cookie cookie = new Cookie("key", "value");

driver.manage().addCookie(cookie);

獲取cookie的值:

// And now output all the available cookies for the current URL

Set<Cookie> allCookies = driver.manage().getCookies();

for (Cookie loadedCookie : allCookies) {

   System.out.println(String.format("%s -> %s",loadedCookie.getName(), loadedCookie.getValue()));

}

根據某個cookie的name獲取cookie的值:

driver.manage().getCookieNamed("mmsid");

刪除cookie:

// You can delete cookies in 3 ways

// By name

driver.manage().deleteCookieNamed("CookieName");

// By Cookie

driver.manage().deleteCookie(loadedCookie);

// Or all of them

driver.manage().deleteAllCookies();

3.3.3 呼叫Java Script

Web driver對Java Script的呼叫是通過JavascriptExecutor來實現的,例如:

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+ inventoryId + "','" + fieldName + "','"

                + value + "');})()");

3.3.4 Webdriver截圖

如果用webdriver截圖是:

driver = webdriver.Firefox()
driver.save_screenshot("C:\error.jpg")

3.3.5 頁面等待

因為Load頁面需要一段時間,如果頁面還沒載入完就查詢元素,必然是查詢不到的。最好的方式,就是設定一個預設等待時間,在查詢頁面元素的時候如果找不到就等待一段時間再找,直到超時。

Webdriver提供兩種方法,一種是顯性等待,另一種是隱性等待。

顯性等待:

WebDriver driver =new FirefoxDriver();

driver.get("http://somedomain/url_that_delays_loading");

WebElementmyDynamicElement = (new WebDriverWait(driver, 10))

  .until(newExpectedCondition<WebElement>(){

  @Override

  public WebElementapply(WebDriver d) {

    returnd.findElement(By.id("myDynamicElement"));

  }});

隱性等待:

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.get("http://somedomain/url_that_delays_loading");

WebElement myDynamicElement =driver.findElement(By.id("myDynamicElement"));

第4章        RemoteWebDriver

當本機上沒有瀏覽器,需要遠端呼叫瀏覽器進行自動化測試時,需要用到RemoteWebDirver.

4.1   使用RemoteWebDriver

import java.io.File;

import java.net.URL;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.remote.Augmenter;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {

    public void myTest()throws Exception {

        WebDriver driver = newRemoteWebDriver(

                               new URL("http://localhost:4446/wd/hub"),

                               DesiredCapabilities.firefox());

       driver.get("http://www.google.com");

        // RemoteWebDriverdoes not implement the TakesScreenshot class

        // if the driver doeshave the Capabilities to take a screenshot

        // then Augmenter willadd the TakesScreenshot methods to the instance

        WebDriveraugmentedDriver = new Augmenter().augment(driver);

        File screenshot =((TakesScreenshot)augmentedDriver).

                            getScreenshotAs(OutputType.FILE);

    }

}

4.2   SeleniumServer

在使用RemoteDriver時,必須在遠端伺服器啟動一個SeleniumServer:

java -jar selenium-server-standalone-2.20.0.jar -port 4446

profile = new FirefoxProfile();

           profile.setPreference("general.useragent.override",testData.getUserAgent()); 

capabilities = DesiredCapabilities.firefox();

capabilities.setCapability("firefox_profile", profile);

driver = new RemoteWebDriver(new URL(“http://localhost:4446/wd/hub”),capabilities);

driverWait = new WebDriverWait(driver,TestConstant.WAIT_ELEMENT_TO_LOAD);

driver.get("http://www.google.com");

第5章        封裝與重用

WebDriver對頁面的操作,需要找到一個WebElement,然後再對其進行操作,比較繁瑣:

 // Find the text inputelement by its name

WebElement element = driver.findElement(By.name("q"));

// Enter something to search for

element.sendKeys("Cheese!");

我們可以考慮對這些基本的操作進行一個封裝,簡化操作。比如,封裝程式碼:

    protected void sendKeys(Byby, String value){

       driver.findElement(by).sendKeys(value);

    }

那麼,在測試用例可以這樣簡化呼叫:

sendKeys(By.name("q"),”Cheese!”);

看,這就簡潔多了。

類似的封裝還有:

package com.drutt.mm.end2end.actions;

import java.util.List;

import java.util.NoSuchElementException;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

import com.drutt.mm.end2end.data.TestConstant;

public class WebDriverAction {

   //protected WebDriverdriver;

   protected RemoteWebDriverdriver;

   protected WebDriverWaitdriverWait;

    protected booleanisWebElementExist(By selector) {

        try {

            driver.findElement(selector);

            return true;

        } catch(NoSuchElementException e) {

            return false;

        }

    }

    protected StringgetWebText(By by) {

        try {

        return driver.findElement(by).getText();

        } catch (NoSuchElementException e) {

            return "Textnot existed!";

        }

    }

    protected voidclickElementContainingText(By by, String text){

        List<WebElement>elementList = driver.findElements(by);

        for(WebElement e:elementList){

            if(e.getText().contains(text)){

                e.click();

                break;

            }

        }    

    }

    protected StringgetLinkUrlContainingText(By by, String text){

        List<WebElement>subscribeButton = driver.findElements(by);

        String url = null;

        for(WebElement e:subscribeButton){

            if(e.getText().contains(text)){

                url =e.getAttribute("href");

                break;

            }

        }

        return url;

    }

    protected void click(Byby){

       driver.findElement(by).click();

       driver.manage().timeouts().implicitlyWait(TestConstant.WAIT_ELEMENT_TO_LOAD,TimeUnit.SECONDS);

    }

    protected StringgetLinkUrl(By by){

        return driver.findElement(by).getAttribute("href");

    }

    protected void sendKeys(Byby, String value){

       driver.findElement(by).sendKeys(value);

    }

第6章        在selenium2.0中使用selenium1.0的API

Selenium2.0中使用WeDriver API對頁面進行操作,它最大的優點是不需要安裝一個selenium server就可以執行,但是對頁面進行操作不如selenium1.0的Selenium RC API那麼方便。Selenium2.0提供了使用Selenium RC API的方法:

// You may use any WebDriver implementation. Firefox is used hereas an example

WebDriver driver = new FirefoxDriver();

// A "base url", used by selenium to resolve relativeURLs

 String baseUrl ="http://www.google.com";

// Create the Selenium implementation

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

// Perform actions with selenium

selenium.open("http://www.google.com");

selenium.type("name=q", "cheese");

selenium.click("name=btnG");

// Get the underlying WebDriver implementation back. This willrefer to the

// same WebDriver instance as the "driver" variableabove.

WebDriver driverInstance = ((WebDriverBackedSelenium)selenium).getUnderlyingWebDriver();

    //Finally, close thebrowser. Call stop on the WebDriverBackedSelenium instance

    //instead of callingdriver.quit(). Otherwise, the JVM will continue running after

    //the browser has beenclosed.

    selenium.stop();

我分別使用WebDriver API和SeleniumRC API寫了一個Login的指令碼,很明顯,後者的操作更加簡單明瞭。

WebDriver API寫的Login指令碼:

    public void login() {

        driver.switchTo().defaultContent();

        driver.switchTo().frame("mainFrame");

        WebElement eUsername= waitFindElement(By.id("username"));

        eUsername.sendKeys([email protected]);

        WebElement ePassword= waitFindElement(By.id("password"));

        ePassword.sendKeys(manager);

        WebElementeLoginButton = waitFindElement(By.id("loginButton"));

       eLoginButton.click();

    }

SeleniumRC API寫的Login指令碼:

    public void login() {

        selenium.selectFrame("relative=top");

        selenium.selectFrame("mainFrame");

        selenium.type("username","[email protected]");

        selenium.type("password","manager");

        selenium.click("loginButton");

}


相關推薦

webdriver API中文版詳細介紹

說明: WebDriver與之前Selenium的JS注入實現不同,直接利用了瀏覽器native support來操作瀏覽器。所以對於不同平臺,不同的瀏覽器,必須依賴一個特定的瀏覽器的native component來實現把WebDriver API的呼叫轉化為瀏

Thread API詳細介紹

正常 class vat 串行 怎麽 需求 arr \n 暗示 import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurr

三、JAVA多執行緒:Thread API詳細介紹 (sleep、Interrupt、Join、TimeUnit、yield、interrupted、執行緒優先順序 )

 本章深入分析了Thread的所有API,熟練掌握Thread的API是學好Thread的前提。   執行緒sleep sleep是一個靜態方法,一共有兩個過載方法,一個需要傳入毫秒數,另一個既要傳入毫秒數又要傳入納秒數。   sleep方法介紹

(二)underscore.js框架Utility類API學習以及模型template的詳細介紹

本文介紹的是underscore.js提供的Utility Functions。 noConflict_.noConflict()Give control of the "_" variable back to its previous owner. Returns a

(轉)Windows API User32.dll詳細介紹

RegisterServiceProcess(ProcessID:Long,Type:Long) 該函式存在於Kernal32.dll中. Process指向程序的ID,Type表示是否向系統註冊該程序,是1,否0.= = = = = = = = = = = = = = =

RabbitMQ基礎概念詳細介紹

可用性 將不 tar connect 相互 abi 封裝 編寫 綁定 原文地址:http://www.diggerplus.org/archives/3110 引言 你是否遇到過兩個(多個)系統間需要通過定時任務來同步某些數據?你是否在為異構系統的不同進程間相互調用、通

dede_archives文章主表詳細介紹

small 選項 key 標題 varchar col cms cores ann dedecms二次開發目錄點這個:dedecms二次開發教程目錄 字段 類型 整理 屬性 Null 默認 額外 id mediumin

JS 事件綁定、事件監聽、事件委托詳細介紹

兼容性 log 查看 and == 常用 提高 監聽 live 事件綁定 要想讓 JavaScript 對用戶的操作作出響應,首先要對 DOM 元素綁定事件處理函數。所謂事件處理函數,就是處理用戶操作的函數,不同的操作對應不同的名稱。 在JavaScript中,有三種常用的

dede_addonimages圖片附加表主表詳細介紹

image 下載 復制 ati logs top 選項 span lsp dedecms二次開發目錄點這個:dedecms二次開發教程目錄 字段 類型 整理 屬性 Null 默認 額外 aid mediumint(

hibernate主鍵詳細介紹

tab merge ren net 對象 num rac 16進制 鍵值 /** * * @author liuguangyi * @content ejb3註解的API定義在javax.persistence.*包裏面。 * * 註釋說

dede_arctype欄目表主表詳細介紹

back 支持 模板 綁定 是否 index color type left dedecms二次開發目錄點這個:dedecms二次開發教程目錄 字段 類型 整理 屬性 Null 默認 額外 id smallint(

HTML中Css詳細介紹

維護 類型 html 外部 -html css樣式 樣式表 作用 tex 一、樣式表的作用  1、Css樣式表,層疊樣式表  2、類似於人類的衣服,網頁的衣服  3、作用:美化網頁  4、優勢:     1.內容與表現分離,便於維護     2.樣式豐富,頁面布局靈活   

文件上傳到tomcat服務器 commons-fileupload的詳細介紹與使用

部分 中文字符 form 引用 編碼 path -type dex item 三個類:DiskFileUpload、FileItem和FileUploadException。這三個類全部位於org.apache.commons.fileupload包中。 首先需要說明一下f

氚雲CRM產品的詳細介紹

銷售管理 銷售人員 聯系人 產品 管理者 1 產品價值1.1 核心優勢 1.2 銷售管理者的煩惱 1.3 產品價值-解決銷售人員的煩惱 1.4 氚雲CRM幫助企業提高工作效率、促進團隊業績順利達成從客戶開發、外勤,聯系人的維護,客戶的跟進商機的有效推進到合同的簽定成交以及發票、回款等銷售生

rabbitMQ概念詳細介紹

end 使用 hosts 性能 benefit 路由 相關 大型網站 進行 1. 歷史 RabbitMQ是一個由erlang開發的AMQP(Advanced Message Queue )的開源實現。AMQP 的出現其實也是應了廣大人民群眾的需求,雖然在同步消息通訊

A10 負載均衡模擬器下載安裝及license免費激活詳細介紹

負載均衡 f5 a10 模擬器下載 A10 Networks官網免費提供Vthunder模擬器下載,並免費提供30天、5Mbps吞吐全功能模塊的License;獲取方法如下:1、首先,登錄A10 Networks官網,提交Vthunder模擬下載申請,申請地址:https://glm.a10n

Linux目錄結構詳細介紹(一)

linux 目錄結構 頂點 / ,其它所有目錄都在根下根下面的目錄及目錄裏的子目錄是一個有層次的倒掛樹狀結構目錄描述/處於linux系統樹形結構的最頂端,它是linux文件系統的入口,所有的目錄、文件、設備都在/之下。/bin/bin是Binary的縮寫,存放著linux系統命令。/boot/包括內核

詳細介紹Java虛擬機(JVM)

委托 article log flow 包括 源代碼 filename method 獨立 1. JVM生命周期 啟動。啟動一個Java程序時,一個JVM實例就產生了,任何一個擁有public static void main(String[] args)函數的class

一.Select 函數詳細介紹【轉】

perror socket編程 這樣的 發生 結構體 阻塞 get 成功 系統 轉自:http://www.cnblogs.com/hjslovewcl/archive/2011/03/16/2314330.html Select在Socket編程中還是比較重

java線程詳細介紹

star 異步 alt 繼承 問題 喚醒 sof 指定 cti 目錄(?)[-] 一擴展javalangThread類 二實現javalangRunnable接口 三Thread和Runnable的區別 四線程狀態轉換 五線程調度 六常用函數說明 使用方式 為什麽要用j