1. 程式人生 > >webDriver入門 selenium 基礎知識與例項

webDriver入門 selenium 基礎知識與例項

1.開啟一個測試瀏覽器

對瀏覽器進行操作首先需要開啟一個瀏覽器,接下來才能對瀏覽器進行操作。

Java程式碼

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxBinary;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.ie.InternetExplorerDriver;

public class OpenBrowsers {

         public static void main(String[] args) {

                   //開啟預設路徑的firefox

                   WebDriver diver = new FirefoxDriver();

                   //開啟指定路徑的firefox,方法1

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\MozillaFirefox\\firefox.exe");

                   WebDriver dr = new FirefoxDriver();

                   //開啟指定路徑的firefox,方法2

                   File pathToFirefoxBinary = newFile("D:\\Program Files\\Mozilla Firefox\\firefox.exe"); 

                   FirefoxBinary firefoxbin = newFirefoxBinary(pathToFirefoxBinary); 

                   WebDriver driver1 = newFirefoxDriver(firefoxbin,null);

                   //開啟ie

                   WebDriver ie_driver = new InternetExplorerDriver();

                   //開啟chrome

                   System.setProperty("webdriver.chrome.driver","D:\\chromedriver.exe");

                   System.setProperty("webdriver.chrome.bin",

                                            "C:\\Documents and Settings\\gongjf\\Local Settings"

                                             +"\\ApplicationData\\Google\\Chrome\\Application\\chrome.exe");

         }

}

2.開啟1個具體的url

開啟一個瀏覽器後,我們需要跳轉到特定的url下,看下面程式碼:

Java程式碼

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class OpenUrl {

         publicstatic void main(String []args){

                   Stringurl = "http://www.51.com";

                   WebDriverdriver = new FirefoxDriver();

                   //用get方法

                   driver.get(url);

                   //用navigate方法,然後再呼叫to方法

                   driver.navigate().to(url);

         }

}

3.如何關閉瀏覽器

測試完成後,需要關閉瀏覽器

Java程式碼

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class CloseBrowser {

         publicstatic void main(String []args){

                   Stringurl = "http://www.51.com";

                   WebDriverdriver = new FirefoxDriver();

                   driver.get(url);

                   //用quit方法

                   driver.quit();

                   //用close方法       

                   driver.close();

                   }

}

4.如何返回當前頁面的url和title

有時候我們需要返回當前頁面的url或者title做一些驗證性的操作等。程式碼如下:

Java程式碼

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class GetUrlAndTitle {

         publicstatic void main(String []args){

                   Stringurl = "http://www.google.com";

                   WebDriverdriver = new FirefoxDriver();

                   driver.get(url);

                //得到title

                   Stringtitle = driver.getTitle();

                //得到當前頁面url

                   StringcurrentUrl = driver.getCurrentUrl();

                //輸出title和currenturl

                   System.out.println(title+"\n"+currentUrl);

                   }

}

5.其他方法

getWindowHandle()    返回當前的瀏覽器的視窗控制代碼

getWindowHandles()  返回當前的瀏覽器的所有視窗控制代碼

getPageSource()        返回當前頁面的原始碼

從上面程式碼可以看出操作瀏覽器的主要方法都來自org.openqa.selenium.WebDriver這個介面中。看了一下原始碼這些方法都是在org.openqa.selenium.remote.RemoteWebDriver這個類中實現的,然後不同瀏覽的driver類繼承RemoteWebDriver。

C  定位頁面元素

selenium-webdriver提供了強大的元素定位方法,支援以下三種方法。

單個物件的定位方法

多個物件的定位方法

層級定位 

定位單個元素

在定位單個元素時,selenium-webdriver提示瞭如下一些方法對元素進行定位。

 By.className(className))    

 By.cssSelector(selector)       

 By.id(id)                     

 By.linkText(linkText)          

 By.name(name)             

 By.partialLinkText(linkText)

 By.tagName(name)       

 By.xpath(xpathExpression)  

注意:selenium-webdriver通過findElement()\findElements()等find方法呼叫"By"物件來定位 和查詢元素。By類只是提供查詢的方式進行分類。findElement返回一個元素物件否則丟擲異常,findElements返回符合條件的元素 List,如果不存在符合條件的就返回一個空的list。

1.使用className進行定位

當所定位的元素具有class屬性的時候我們可以通過classname來定位該元素。

下面的例子定位了51.com首頁上class為"username"的li。

Java程式碼

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.By;

public class ByClassName {

   public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();

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

        WebElement element =driver.findElement(By.className("username"));

        System.out.println(element.getTagName());

    }

}

輸出結果:

Java程式碼

Li

2.使用id屬性定位

51.com首頁的帳號輸入框的html程式碼如下:

Java程式碼

<input id="passport_51_user"type="text" value="" tabindex="1" title="使用者名稱/彩虹號/郵箱"

name="passport_51_user">

在下面的例子中用id定位這個輸入框,並輸出其title,藉此也可以驗證程式碼是否工作正常。

Java程式碼

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class ByUserId {

         /**

          * @param args

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

                   WebElementelement = dr.findElement(By.id("passport_51_user"));

                   System.out.println(element.getAttribute("title"));

         }

}

輸出結果:

 Java程式碼

使用者名稱/彩虹號/郵箱

3.使用name屬性定位

51.com首頁的帳號輸入框的html程式碼如下:

Java程式碼

<input id="passport_51_user"type="text" value="" tabindex="1" title="使用者名稱/彩虹號/郵箱"

name="passport_51_user">

使用name定位

Java程式碼

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class ByUserId {

         /**

          * @param args

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

         WebElemente = dr.findElement(By.name("passport_51_user"));                                      System.out.println(element.getAttribute("title"));

         }

}

輸出結果:

 Java程式碼

使用者名稱/彩虹號/郵箱

4.使用css屬性定位

51.com首頁的帳號輸入框的html程式碼如下:

Java程式碼

<input id="passport_51_user"type="text" value="" tabindex="1" title="使用者名稱/彩虹號/郵箱"

name="passport_51_user">

使用css定位

Java程式碼

WebElement e1 =dr.findElement(By.cssSelector("#passport_51_user"));

5.使用 XPATH定位

51.com首頁的帳號輸入框的html程式碼如下:

Java程式碼

<input id="passport_51_user"type="text" value="" tabindex="1" title="使用者名稱/彩虹號/郵箱"

name="passport_51_user">

通過xpath查詢:

Java程式碼

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

6.使用其他方式定位

在定位link元素的時候,可以使用link和link_text屬性;

另外還可以使用tag_name屬性定位任意元素;

7.定位多個元素

上面提到findElements()方法可以返回一個符合條件的元素List組。看下面例子。

Java程式碼

import java.io.File;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxBinary;

import org.openqa.selenium.firefox.FirefoxDriver;

public class FindElementsStudy {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   WebDriver  driver = new FirefoxDriver();

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

                   //定位到所有<input>標籤的元素,然後輸出他們的id

                   List<WebElement>element = driver.findElements(By.tagName("input"));

                   for(WebElement e : element){

                            System.out.println(e.getAttribute("id"));

                   }

                   driver.quit();

         }

}

輸出結果:

Java程式碼

passport_cookie_login

gourl

passport_login_from

passport_51_user

passport_51_password

passport_qq_login_2

btn_reg

passport_51_ishidden

passport_auto_login

上面的程式碼返回頁面上所有input物件

8.層級定位

層級定位的思想是先定位父元素,然後再從父元素中精確定位出其我們需要選取的子元素。

層級定位一般的應用場景是無法直接定位到需要選取的元素,但是其父元素比較容易定位,通過定位父元素再遍歷其子元素選擇需要的目標元素,或者需要定位某個元素下所有的子元素。

下面的程式碼演示瞭如何使用層級定位class為"login"的div,然後再取得它下面的所有label,並打印出他們的文字

Java程式碼

importjava.util.List;

importorg.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxBinary;

importorg.openqa.selenium.firefox.FirefoxDriver;

publicclass LayerLocator {

         /**

          * @author gongjf

          */

         public static void main(String[] args){

                   WebDriver  driver = new FirefoxDriver();

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

                   //定位class為"login"的div,然後再取得它下面的所有label,並打印出他們的值

                   WebElement element =driver.findElement(By.className("login"));

                    List<WebElement> el =element.findElements(By.tagName("label"));

                    for(WebElement e : el)

                   System.out.println(e.getText());

         }       

}

輸出結果:

Java程式碼

帳號:

密碼:

隱身

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

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

1. 輸入框(text field or textarea)

 找到輸入框元素:

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

在輸入框中輸入內容:

element.sendKeys(“test”);

將輸入框清空:

element.clear();

獲取輸入框的文字內容:

element.getText();

2. 下拉選擇框(Select)

找到下拉選擇框的元素:

Select select = newSelect(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();

對下拉框進行操作時首先要定位到這個下拉框,new 一個Selcet物件,然後對它進行操作 

3. 單選項(Radio Button)

找到單選框元素:

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

選擇某個單選項:

bookMode.click();

清空某個單選項:

bookMode.clear();

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

bookMode.isSelected();

4. 多選項(checkbox)

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

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

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

5. 按鈕(button)

找到按鈕元素:

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

點選按鈕:

saveButton.click();

判斷按鈕是否enable:

saveButton.isEnabled ();

6. 左右選擇框

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

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

lang.selectByVisibleText(“English”);

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

addLanguage.click();

7. 彈出對話方塊(Popup dialogs)

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

alert.accept();

alert.dismiss();

alert.getText();

後面有具體的例子解釋~

8. 表單(Form)

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

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

approve.click();

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

9. 上傳檔案 (Upload File)

上傳檔案的元素操作:

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

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

adFileUpload.sendKeys(filePath);

10.拖拉(Drag andDrop)

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

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

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

11.導航 (Navigationand History)

開啟一個新的頁面:

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

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

driver.navigate().forward();

driver.navigate().back();

E  iframe的處理

有時候我們在定位一個頁面元素的時候發現一直定位不了,反覆檢查自己寫的定位器沒有任何問題,程式碼也沒有任何問題。這時你就要看一下這個頁面元素是否在一個iframe中,這可能就是找不到的原因之一。如果你在一個default content中查詢一個在iframe中的元素,那肯定是找不到的。反之你在一個iframe中查詢另一個iframe元素或default content中的元素,那必然也定位不到。

selenium webdriver中提供了進入一個iframe的方法:

WebDriverorg.openqa.selenium.WebDriver.TargetLocator.frame(String nameOrId)

也提供了一個返回default content的方法:

WebDriver org.openqa.selenium.WebDriver.TargetLocator.defaultContent()

這樣使我們面對iframe時可以輕鬆應對。

以下面的html程式碼為例,我們看一下處現iframe。

Html程式碼

main.html

<html>

   <head>

       <title>FrameTest</title>

   </head>

   <body>

         <divid = "id1">this is a div!</div>

       <iframe id = "frame" frameborder="0" scrolling="no"style="left:0;position:absolute;" src ="frame.html"></iframe>

   </body>

</html>

frame.html

<html>

   <head>

       <title>this is a frame!</title>

   </head>

   <body>

         <divid = "div1">this is a div,too!</div>

         <label>input:</label>

         <inputid = "input1"></input>

   </body>

</html>

Java程式碼

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class FameStudy {

         publicstatic void main(String[] args) {

                   WebDriverdr = new FirefoxDriver();

                   Stringurl = "\\Your\\Path\\to\\main.html";

                   dr.get(url);

                   //在defaultcontent定位id="id1"的div

                   dr.findElement(By.id("id1"));

                   //此時,沒有進入到id="frame"的frame中時,以下兩句會報錯

                   dr.findElement(By.id("div1"));//報錯

                   dr.findElement(By.id("input1"));//報錯

                   //進入id="frame"的frame中,定位id="div1"的div和id="input1"的輸入框。

                   dr.switchTo().frame("frame");        

                   dr.findElement(By.id("div1"));

                   dr.findElement(By.id("input1"));

                   //此時,沒有跳出frame,如果定位defaultcontent中的元素也會報錯。

                   dr.findElement(By.id("id1"));//報錯

                   //跳出frame,進入defaultcontent;重新定位id="id1"的div

                   dr.switchTo().defaultContent();

                   dr.findElement(By.id("id1"));

         }

}

小結:

switch_to方法會new1個TargetLocator物件,使用該物件的frame方法可以將當前識別的”主體”移動到需要定位的frame上去。 

F 如何得到彈出視窗

在selenium 1.X裡面得到彈出視窗是一件比較麻煩的事,特別是新開視窗沒有id、name的時候。在selenium webdriver中得到新開視窗相對簡單的多,它無關新開視窗的id、name等屬性。以下面的html為例:

Html程式碼

<span style="white-space: normal;background-color: #ffffff;">test.html</span>

<html>

   <head><title>Test Popup Window</title></head>

   <body>

       <a id = "51" href = "http://www.51.com/" target ="_blank">Let's go!</a>

   </body>

</html>

下面的程式碼演示瞭如何去得到彈出的新視窗

Java程式碼

import java.util.Iterator;

import java.util.Set;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class PopupWindowTest {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   Stringurl ="\\Your\\Path\\to\\main.html";

                   dr.get(url);       

                   dr.findElement(By.id("51")).click();

                   //得到當前視窗的控制代碼

                   StringcurrentWindow = dr.getWindowHandle();

                   //得到所有視窗的控制代碼

                   Set<String>handles = dr.getWindowHandles();

                   Iterator<String>it = handles.iterator();

                   while(it.hasNext()){

                            if(currentWindow== it.next())  continue;

                            dr.switchTo().window(it.next());

                   }

         }

}

輸出結果:

title,url = 51.com 真人配對玩遊戲,http://www.51.com/

小結:

捕獲或者說定位彈出視窗的關鍵在於獲得彈出視窗的控制代碼。(

在上面的程式碼裡,使用windowhandle方法來獲取當前瀏覽器視窗的控制代碼,使用了windowhandles方法獲取所有彈出的瀏覽器視窗的控制代碼,然後通過排除當前控制代碼的方法來得到新開視窗的控制代碼。

在獲取新彈出視窗的控制代碼後,使用switchto.window(newwindow_handle)方法,將新視窗的控制代碼作為引數傳入既可捕獲到新視窗了。

如果想回到以前的視窗定位元素,那麼再呼叫1次switchto.window方法,傳入之前視窗的控制代碼既可達到目的。

G  如何處理alert、confirm、prompt對話方塊

alert、confirm、prompt這樣的js對話方塊在selenium1.X時代也是難啃的骨頭,常常要用autoit來幫助處理。

試用了一下selenium webdriver中處理這些對話方塊十分方便簡潔

Html程式碼

Dialogs.html  

<html>

   <head>

       <title>Alert</title>

   </head>

   <body>

       <input id = "alert" value = "alert" type ="button" onclick = "alert('歡迎!請按確認繼續!');"/>

        <input id = "confirm" value= "confirm" type = "button" onclick = "confirm('確定嗎?');"/>

         <inputid = "prompt" value = "prompt" type = "button"onclick = "var name = prompt('請輸入你的名字:','請輸入

你的名字'); document.write(name) "/>

   </body>

</html>

 以上html程式碼在頁面上顯示了三個按鈕,點選他們分別彈出alert、confirm、prompt對話方塊。如果在prompt對話方塊中輸入文字點選確定之後,將會重新整理頁面,顯示出這些文字。

selenium webdriver 處理這些彈層的程式碼如下:

Java程式碼

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class DialogsStudy {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   Stringurl = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Dialogs.html";//"/Your/Path/to/main.html"

                   dr.get(url);

                   //點選第一個按鈕,輸出對話方塊上面的文字,然後叉掉

                   dr.findElement(By.id("alert")).click();

                   Alertalert = dr.switchTo().alert();

                   Stringtext = alert.getText();

                   System.out.println(text);

                   alert.dismiss();

                   //點選第二個按鈕,輸出對話方塊上面的文字,然後點選確認

                   dr.findElement(By.id("confirm")).click();

                   Alertconfirm = dr.switchTo().alert();

                   Stringtext1 = confirm.getText();

                   System.out.println(text1);

                   confirm.accept();

                   //點選第三個按鈕,輸入你的名字,然後點選確認,最後

                   dr.findElement(By.id("prompt")).click();

                   Alertprompt = dr.switchTo().alert();

                   Stringtext2 = prompt.getText();

                   System.out.println(text2);

                   prompt.sendKeys("jarvi");

                   prompt.accept();

         }

}

小結:

從以上程式碼可以看出dr.switchTo().alert();這句可以得到alert\confirm\prompt對話方塊的物件,然後運用其方法對它進行操作。對話方塊操作的主要方法有:

getText()    得到它的文字值

accept()      相當於點選它的"確認"

dismiss()     相當於點選"取消"或者叉掉對話方塊

sendKeys() 輸入值,這個alert\confirm沒有對話方塊就不能用了,不然會報錯。

H  如何操作cookies

Web 測試中我們經常會接觸到Cookies,一個Cookies主要屬性有”所在域、name、value、有效日期和路徑",下面來講一下怎麼操作Cookies

Java程式碼

import java.util.Set;

import org.openqa.selenium.Cookie;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class CookiesStudy {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

                   //增加一個name ="name",value="value"的cookie

                   Cookiecookie = new Cookie("name", "value");

                   dr.manage().addCookie(cookie);

                   //得到當前頁面下所有的cookies,並且輸出它們的所在域、name、value、有效日期和路徑

                   Set<Cookie>cookies = dr.manage().getCookies();

                   System.out.println(String.format("Domain-> name -> value -> expiry -> path"));

                   for(Cookiec : cookies)

                            System.out.println(String.format("%s-> %s -> %s -> %s -> %s",

                                               c.getDomain(),c.getName(), c.getValue(),c.getExpiry(),c.getPath()));

                   //刪除cookie有三種方法

                   //第一種通過cookie的name

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

                   //第二種通過Cookie物件

                   dr.manage().deleteCookie(cookie);

                   //第三種全部刪除

                   dr.manage().deleteAllCookies();

         }

小結:

上面的程式碼首先在頁面中增加了一個cookie,然後遍歷頁面的所有cookies,並輸出他們的主要屬性。最後就是三種刪除cookie的方法。

I  如何等待頁面元素載入完成

web的自動化測試中,我們經常會遇到這樣一種情況:當我們的程式執行時需要頁面某個元素,而此時這個元素還未載入完成,這時我們的程式就會報錯。怎麼辦?等待。等待元素出現後再進行對這個元素的操作。

在selenium-webdriver中我們用兩種方式進行等待:明確的等待和隱性的等待。

明確的等待

明確的等待是指在程式碼進行下一步操作之前等待某一個條件的發生。最不好的情況是使用Thread.sleep()去設定一段確認的時間去等待。但為什麼說最不好呢?因為一個元素的載入時間有長有短,你在設定sleep的時間之前要自己把握長短,太短容易超時,太長浪費時間。selenium webdriver提供了一些方法幫助我們等待正好需要等待的時間。利用WebDriverWait類和ExpectedCondition介面就能實現這一點。

下面的html程式碼實現了這樣的一種效果:點選click按鈕5秒鐘後,頁面上會出現一個紅色的div塊。我們需要寫一段自動化指令碼去捕獲這個出現的div,然後高亮之。

Html程式碼

Wait.html

<html>

   <head>

       <title>Set Timeout</title>

       <style>

           .red_box {background-color: red; width = 20%; height: 100px; border:none;}

       </style>

       <script>

           function show_div(){

               setTimeout("create_div()", 5000);

           }

           function create_div(){

                d =document.createElement('div');

                d.className ="red_box";

                document.body.appendChild(d);

           }

       </script>

   </head>

   <body>

       <button id = "b" onclick ="show_div()">click</button>

   </body>

</html>

下面的程式碼實現了高亮動態生成的div塊的功能:

Java程式碼

import org.openqa.selenium.By;

importorg.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.support.ui.ExpectedCondition;

importorg.openqa.selenium.support.ui.WebDriverWait;

public class WaitForSomthing {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   Stringurl = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Wait.html";//"/Your/Path/to/Wait.html"

                   dr.get(url);

                   WebDriverWaitwait = new WebDriverWait(dr,10);

                   wait.until(newExpectedCondition<WebElement>(){

                            @Override

                            publicWebElement apply(WebDriver d) {

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

                            }}).click();

                   WebElementelement = dr.findElement(By.cssSelector(".red_box"));

                   ((JavascriptExecutor)dr).executeScript("arguments[0].style.border= \"5px solid yellow\"",element); 

         }

}

上面的程式碼WebDriverWait類的構造方法接受了一個WebDriver物件和一個等待最長時間(10秒)。然後呼叫until方法,其中重寫了 ExpectedCondition介面中的apply方法,讓其返回一個WebElement,即載入完成的元素,然後點選。預設情況下,WebDriverWait每500毫秒呼叫一次ExpectedCondition,直到有成功的返回,當然如果超過設定的值還沒有成功的返回,將丟擲異常。

隱性等待

隱性等待是指當要查詢元素,而這個元素沒有馬上出現時,告訴WebDriver查詢Dom一定時間。預設值是0,但是設定之後,這個時間將在WebDriver物件例項整個生命週期都起作用。上面的程式碼就變成了這樣:

Java程式碼

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

importorg.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.support.ui.ExpectedCondition;

importorg.openqa.selenium.support.ui.WebDriverWait;

public class WaitForSomthing {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   //設定10秒

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

                   Stringurl = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Wait.html";//"/Your/Path/to/Wait.html"

                   dr.get(url);

                 //註釋掉原來的

                   /*WebDriverWaitwait = new WebDriverWait(dr,10);

                   wait.until(newExpectedCondition<WebElement>(){

                            @Override

                            publicWebElement apply(WebDriver d) {

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

                            }}).click();*/

                   dr.findElement(By.id("b")).click();

                   WebElementelement = dr.findElement(By.cssSelector(".red_box"));

                   ((JavascriptExecutor)dr).executeScript("arguments[0].style.border= \"5px solid yellow\"",element); 

         }

}

小結:

兩種方法任選其一

J  如何利用selenium-webdriver截圖

在自動化測試中常常會用到截圖功能。可以擷取頁面全圖,不管頁面有多長。

下面的程式碼演示瞭如何使用webdriver進行截圖:

Java程式碼

import java.io.File;

import java.io.IOException;

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class ShotScreen {

         /**

          * @author gongjf

          * @throws IOException

          * @throws InterruptedException

          */

         publicstatic void main(String[] args) throws IOException, InterruptedException {

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

                   //這裡等待頁面載入完成

                   Thread.sleep(5000);

                   //下面程式碼是得到截圖並儲存在D盤下

                   FilescreenShotFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);

                   FileUtils.copyFile(screenShotFile,new File("D:/test.png"));

}

}

K  封裝與重用

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

 // Find the text inputelement by itsname

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

// Enter something to search for

element.sendKeys("Cheese!");

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

    protected voidsendKeys(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;

importorg.openqa.selenium.remote.RemoteWebDriver;

importorg.openqa.selenium.support.ui.WebDriverWait;

importcom.drutt.mm.end2end.data.TestConstant;

public class WebDriverAction {

   //protected WebDriverdriver;

   protectedRemoteWebDriverdriver;

   protectedWebDriverWaitdriverWait;

    protected booleanisWebElementExist(Byselector) {

       try {

           driver.findElement(selector);

           return true;

       } catch(NoSuchElementException e) {

           return false;

       }

    }

    protectedStringgetWebText(By by) {

       try {

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

       } catch (NoSuchElementException e) {

           return "Textnot existed!";

       }

    }

    protectedvoidclickElementContainingText(By by, String text){

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

       for(WebElement e:elementList){

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

               e.click();

               break;

           }

       }    

    }

    protectedStringgetLinkUrlContainingText(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 voidclick(Byby){

       driver.findElement(by).click();

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

    }

    protectedStringgetLinkUrl(By by){

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

    }

    protected voidsendKeys(Byby, String value){

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

    }

小結:

按照上面的例子你可以對各個方法進行封裝,使自己的程式碼更加簡潔!

L  在selenium2.0中使用selenium1.0的API

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

// 我用火狐瀏覽器作為例子

WebDriver driver = newFirefoxDriver(); 

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

Selenium selenium = newWebDriverBackedSelenium(driver, baseUrl);

// 執行selenium命令

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

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

selenium.click("name=btnG");

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

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入門 selenium 基礎知識例項

1.開啟一個測試瀏覽器 對瀏覽器進行操作首先需要開啟一個瀏覽器,接下來才能對瀏覽器進行操作。 Java程式碼 import org.openqa.selenium.WebDriver; importorg.openqa.selenium.firefox.Firefo

Android自定義View總結(一)基礎知識例項

自定義View是最能體現一個Android開發者水平的技能之一了。 接下來的一些列部落格將總結一下Android的自定義相關View知識,包括View的結構,事件體系,工作原理,自定義View的繪製等。 參考資料部分來自於書上以及各種部落格。 新建了一個qq群 482

Tensorflow基礎知識神經網路構建--step by step 入門TensorFlow(一)

Tensorflow基礎知識與神經網路構建–step by step 入門TensorFlow(一) 標籤: Tensorflow 我們將採用Jupyter notebook互動式程式設計的方式,通過一步步程式碼的講解,學習Tensorflow程式設計。

初識多線程之基礎知識常用方法

splay 線程與進程 -- 實現 class png sleep .com code 1.線程與進程的描述: 1.1進程:每個進程都有獨立的代碼和數據空間(進程上下文),進程間的切換會有較大的開銷,一個進程包含1~n個線程。(進程是資源分配的最小單位)   1.2線程:

Linux入門基礎知識

linux如果操作系統發展史出一部美國大片,那一定是三國硝煙的味道。上世界末的一群西方人,雖沒有西部牛仔的放蕩不羈,也成就了一段令後人難望其項背的歷史。而且,身為Unix之父,Linux之父,計算機開源運動之父,Windows之父,無一例外,都還好好的活在這個他們親眼見證的,不斷發展壯大的信息技術時代。197

爬蟲基礎知識簡單爬蟲實現

春秋 屬性 str 版本 page 2017年 light install defaults css規則:選擇器,以及一條或者多條生命。 selector{declaration1;,,,;desclarationN} 每條聲明是由一個屬性和一個值組成 propert

Chef學習筆記(一)--基礎知識安裝配置

Chef 概念 安裝 配置 示例 通常Chef由三部分組成:Workstation、Chef Server、Chef Node。 Workstation是進行日常工作的機器,需安裝Chef Development Kit,用來編寫cookbooks,管理Chef Server和Node。

docker-基礎知識安裝命令

可擴展 可執行文件 依賴包 卸載 實例 參數 tar 研發 normal docker概念docker是一個平臺,為了讓開發人員和系統管理人員進行研發、部署、運行容器程序的。靈活性:那怕最復雜的應用程序也可以容器化輕量級:容器是利用和分享宿主機的內核可互換:可以動態部署更新

全棧工程師基礎知識筆記

工程 分割線 傾斜 aci all 書寫 開發 單元 國內 一,開發工具:記事本txt;subkime;dreamwear;webstorm;hbulider title 主題,題目, Url 是網址 Body 是網站內容 Body的內容考代碼實現的。 Html 語言超文本

c++編程入門2 基礎知識

str break img gin std 分享圖片 數位 函數 stream c++中的幾種操縱符 1.setw(int)用來設置域寬,就是設置數值的顯示位數 頭文件為iomanip 2.setprecision(int)用來設置浮點數的小數位數(包括小數點) 四舍五入

Unity學習(三)Unity Shader入門基礎知識篇)+線性代數複習(未完待續)

至於為什麼剛建立了指令碼,現在就要做Shader了。。說多了都是淚 1.建立一個新的材質 Material Assert -> Create -> Material 拖到Scene中的某個物體上 2.建立一個新的Shader Assert -> Create -

語音識別的基礎知識CMUsphinx介紹

語音識別的基礎知識與CMUsphinx介紹          語音識別技術就是讓機器通過識別和理解過程把語音訊號轉變為相應的文字或命令的技術。       

健身教練入門基礎知識你都知道嗎?怎麽學習才好?

html follow 知識 趣味 計劃 市場 解剖 實力 指導 眾所周知,無論在什麽行業,都沒有不勞而獲的天才,必須遵循我們俗稱的“一萬個小時定律”,即在一個行業中堅持工作一萬個小時,才能可能成為該方面的專家。 對於許多有意願從事健身行業的人士來說,成為專家尚且言之過早,

Flask學習之基礎知識功能

一:flask的背景介紹 Flask是一個基於Python開發並且依賴jinja2模板和Werkzeug WSGI服務的一個微型框架,對於Werkzeug本質是Socket服務端,其用於接收http請求並對請求進行預處理,然後觸發Flask框架,開發人員基於Flask框架提供的功能對請求進行相應的處理,並返

一、redis系列之基礎知識centos下環境搭建

oracle數據庫 但是 sorted 插入 執行 映射 放松 適合 oracl 1. Redis 與其他 key - value 緩存產品有以下三個特點: Redis支持數據的持久化,可以將內存中的數據保持在磁盤中,重啟的時候可以再次加載進行使用。 Redis不僅僅支持

Java Redis的基礎知識安裝部署記錄

一.基本介紹 1.Redis的基礎資料型別一共有五種 字串(str)、列表(lists)、集合(sets)、有序集合(sorts sets)、雜湊表(hashs) 2.與memcache的區別 1.redis可以用來做儲存(storge),memcache只能用於快取(cache)

瞭解LoRaWAN 基礎知識關鍵技術

  LPWAN與LoRaWAN的關係 LPWAN或稱LPN,全稱為Low Power Wide Area Network或者LowPower Network,指的是一種無線網路。這種無線網路強調低功耗與遠距離,通常用於電池供電的感測器節點組網。        概括來講,L

MongoDB基礎知識常用命令

SQL術語/概念 MongoDB術語/概念 解釋/說明 database database 資料庫 table collection 資料庫表/集合 row docu

nginx入門基礎知識總結

大概兩週的時間完成:   知識點:1.簡單介紹                 2.安裝與啟動   &n

uboot的基礎知識linux啟動相關知識

uboot本質是一個裸機程式 ***uboot在啟動時的作用: 主要是用來啟動作業系統的核心。 部署整個系統。 操作Flash等板子上硬體的驅動,初始化一部分硬體。 提供一個命令列介面供人進行互動操作。 PC機的啟動:上電後先執行BIOS程式(實際上就是Norf