WebDriver入門指南_selenium

來源:互聯網
上載者:User
1.1  下載selenium2.0的lib包

http://code.google.com/p/selenium/downloads/list

 

官方User Guide:http://seleniumhq.org/docs/ 1.2  用webdriver開啟一個瀏覽器

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

  開啟firefox瀏覽器:

        //Create a newinstance of the Firefox driver

        WebDriver driver = newFirefoxDriver();

  開啟IE瀏覽器

        //Create a newinstance of the Internet Explorer driver

        WebDriver driver = newInternetExplorerDriver ();

  開啟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  如何找到頁面元素

Webdriver的findElement方法可以用來找到頁面的某個元素,最常用的方法是用id和name尋找。

 

假設頁面寫成這樣:

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

 

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

通過id尋找:

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

或通過name尋找:

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

或通過xpath尋找:

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

 

但頁面的元素經常在找的時候因為出現得慢而找不到,建議是在尋找的時候等一個時間間隔。 1.5  如何對頁面元素進行操作

找到頁面元素後,怎樣對頁面進行操作呢。我們可以根據不同的類型的元素來進行一一說明。 1.5.1 輸入框(text field or textarea)

   找到輸入框元素:

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

在輸入框中輸入內容:

element.sendKeys(“test”);

將輸入框清空:

element.clear();

擷取輸入框的常值內容:

element.getText();

  1.5.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();

  1.5.3單選項(Radio Button)

找到單選框元素:

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

選擇某個單選項:

bookMode.click();

清空某個單選項:

bookMode.clear();

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

bookMode.isSelected(); 1.5.4多選項(checkbox)

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

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

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled(); 1.5.5按鈕(button)

找到按鈕元素:

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

點擊按鈕:

saveButton.click();

判斷按鈕是否enable:

 

saveButton.isEnabled (); 1.5.6左右選擇框

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

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

lang.selectByVisibleText(“English”);

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

addLanguage.click(); 1.5.7彈出對話方塊(Popup dialogs)

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

alert.accept();

alert.dismiss();

alert.getText(); 1.5.8表單(Form)

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

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

approve.click();

approve.submit();//只適合於表單的提交 1.5.9上傳檔案

上傳檔案的元素操作:

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

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

adFileUpload.sendKeys(filePath); 1.6  Windows 和 Frames之間的切換

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

driver.switchTo().defaultContent();

切換到某個frame:

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

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

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

切換到某個window:

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

  1.7  調用Java Script

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

JavascriptExecutor js = (JavascriptExecutor) driver;

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

                + value + "');})()"); 1.8  頁面等待

頁面的操作比較慢,通常需要等待一段時間,頁面元素才出現,但webdriver沒有提供現成的方法,需要自己寫。

等一段時間再對頁面元素進行操作:

    public void waitForPageToLoad(longtime) {

        try {

            Thread.sleep(time);

        } catch (Exceptione) {

        }

    }

在找WebElement的時候等待:

   public WebElementwaitFindElement(By by) {

        returnwaitFindElement(by, Long.parseLong(CommonConstant.GUI_FIND_ELEMENT_TIMEOUT),Long

                .parseLong(CommonConstant.GUI_FIND_ELEMENT_INTERVAL));

    }

 

    public WebElementwaitFindElement(By by, long timeout, long interval) {

        long start = System.currentTimeMillis();

        while (true) {

            try {

                return driver.findElement(by);

            } catch(NoSuchElementException nse) {

                if (System.currentTimeMillis()- start >= timeout) {

                    throw newError("Timeout reached and element[" + by + "]not found");

                } else {

                    try {

                        synchronized(this) {

                           wait(interval);

                        }

                    } catch(InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            }

        }

    }

  1.9  在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(manager@ericsson.com);

 

        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","manager@ericsson.com");

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

        selenium.click("loginButton");

}

       

      Written by smilingsin GuangZhou , June22th, 2011

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.