Selenium2.0 WebDriver基本操作

http://www.cnblogs.com/dream0577/archive/2012/10/07/2714580.html

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

 打開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([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");

}



發佈了54 篇原創文章 · 獲贊 22 · 訪問量 44萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章