1. 程式人生 > >和我一起學 Selenium WebDriver(1)——入門篇

和我一起學 Selenium WebDriver(1)——入門篇

   zTree 東西不多,我也一直使用著原始的人工測試手段,隨著內容的不斷增多,測試起來就越發的繁雜,而且經常犯懶,這樣就會忽略很多本該發現的問題,而且也容易出現舊的bug 反覆出現的情況,這都是測試不規範造成的。要做好東西就要更加規範和嚴格,於是乎決定要學習一下 Selenium WebDriver,也就是原先的  Selenium v2 了,這方面整體的文章並不多,所以一邊學著,自己一邊整理吧。

    對於這個可以自動化測試的工具( Selenium WebDriver)我就不做過多描述了,去 google、baidu 搜尋一下即可。 我這裡只記錄學習  Selenium WebDriver 的過程,尤其是執行時可能出現的問題,當然了,我是做java的,我只學習 java 與  Selenium WebDriver 配合的方法。



一、下載檔案



  • Selenium IDE (專門用於 FireFox 測試的獨立介面,可以錄製測試步驟,但我更傾向於寫程式碼做標準的功能測試)
  • Selenium Server (可以輸入指令控制、可以解決跨域的 js 問題,等到後面學到了再講吧)
  • The Internet Explorer Driver Server (專門用於IE測試的)
  • Selenium Client Drivers (可以找到你熟悉的語言,例如我選擇的 Java)
  • Third Party Browser Drivers NOT SUPPORTED/DEVELOPED by seleniumhq(第三方開發的 Selenium 外掛,第一個就是 Chrome 的,否則你就沒辦法測試 Chrome 了)
  • 其他的,就根據你自己的需要尋找吧,目前這些足夠我用了。

二、安裝 & 執行

貌似擺弄新東西時,只有 “Hello World” 蹦出來以後,我們這些初學者才會感到情緒穩定,那就趕緊開始吧。

對於初期打算直接用程式設計方式製作測試用例的情況來說,Selenium IDE、Selenium Server 都可以不用安裝執行。

看中文的,就繼續聽我嘮叨:

【1. 建立 Maven 工程】
Selenium 支援 maven 工程,這會讓你的工作更加簡便。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>Selenium2Test</groupId> <artifactId>Selenium2Test</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.25.0</version> </dependency> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> <version>0.16</version> <exclusions> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-remote-driver</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </dependencyManagement> </project>

pom.xml 修改儲存後,eclipse 會自動把需要的 jar 包下載完成。


【2. 測試 FireFox】
Selenium 最初就是在 FireFox 上做起來的外掛,所以我們先來搭建 FireFox 的環境。
確保你正確安裝了 FireFox 後,就可以直接編寫 java 程式碼測試嘍。

在 lesson1 目錄下建立 ExampleForFireFox.java
(因為國內不少朋友訪問 google 的時候會出問題,所以我就把程式碼中的 google 變成 baidu 了)

package lesson1;

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 ExampleForFireFox  {
    public static void main(String[] args) {
    	// 如果你的 FireFox 沒有安裝在預設目錄,那麼必須在程式中設定
//    	System.setProperty("webdriver.firefox.bin", "D:\\Program Files\\Mozilla Firefox\\firefox.exe");
    	// 建立一個 FireFox 的瀏覽器例項
        WebDriver driver = new FirefoxDriver();

        // 讓瀏覽器訪問 Baidu
        driver.get("http://www.baidu.com");
        // 用下面程式碼也可以實現
        // driver.navigate().to("http://www.baidu.com");

        // 獲取 網頁的 title
        System.out.println("1 Page title is: " + driver.getTitle());

        // 通過 id 找到 input 的 DOM
        WebElement element = driver.findElement(By.id("kw"));

        // 輸入關鍵字
        element.sendKeys("zTree");

        // 提交 input 所在的  form
        element.submit();
        
        // 通過判斷 title 內容等待搜尋頁面載入完畢,Timeout 設定10秒
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().endsWith("ztree");
            }
        });

        // 顯示搜尋結果頁面的 title
        System.out.println("2 Page title is: " + driver.getTitle());
        
        //關閉瀏覽器
        driver.quit();
    }
}

普通情況下,直接執行程式碼就可以看到會自動彈出 FireFox 視窗,訪問 baidu.com,然後輸入關鍵字並查詢,一切都是自動完成的。

錯誤提醒:
1)Exception in thread "main" org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed.
出現這個錯誤,是說明你的 FireFox 檔案並沒有安裝在預設目錄下,這時候需要在最開始執行:System.setProperty 設定環境變數  "webdriver.firefox.bin" 將自己機器上 FireFox 的正確路徑設定完畢後即可。

2)Exception in thread "main" org.openqa.selenium.UnsupportedCommandException: Bad request

出現這個錯誤,很有意思。 查了一下 有人說應該是 hosts 出現了問題,加上一個 127.0.0.1  localhost 就行了,但我的 hosts 上肯定有這個玩意,為啥也會出現這個問題呢? 

經過除錯,發現 127.0.0.1 localhost 的設定必須要在 hosts 檔案的最開始,而且如果後面有其他設定後,也不要再出現同樣的 127.0.0.1 localhost ,只要有就會出錯。(因為我為了方便訪問 google 的網站,專門加入了 smarthosts 的內容,導致了 localhost 的重複)

【3. 測試 Chrome】
Chrome 雖然不是 Selenium 的原配,但是沒辦法,她太火辣了,絕對不能拋下她不管的。
把 ExampleForFireFox.java 稍微修改就可以製作出一個 ExampleForChrome.java ,直接把 new FireFoxDriver() 修改為 new ChromeDriver() 你會發現還是行不通。

錯誤如下:
1)Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
這應該是找不到 chrome 的檔案,好吧,利用 System.setProperty 方法新增路徑,這裡要注意,是 “webdriver.chrome.driver” 可不是“webdriver.chrome.bin

設定路徑後還是會報錯:
2)[6416:4580:1204/173852:ERROR:gpu_info_collector_win.cc(91)] Can't retrieve a valid WinSAT assessment.
這個貌似是因為 Selenium 無法直接啟動 Chrome 導致的,必須要通過前面咱們下載 Chrome 的第三方外掛 ChromeDriver,去看第一個錯誤中提示給你的 網址:http://code.google.com/p/selenium/wiki/ChromeDriver
按照人家給的例子來修改我們的測試程式碼吧:

package lesson1;

import java.io.File;
import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ExampleForChrome {
    public static void main(String[] args) throws IOException {
        // 設定 chrome 的路徑
        System.setProperty(
                "webdriver.chrome.driver",
                "C:\\Documents and Settings\\sq\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe");
        // 建立一個 ChromeDriver 的介面,用於連線 Chrome
        @SuppressWarnings("deprecation")
        ChromeDriverService service = new ChromeDriverService.Builder()
                .usingChromeDriverExecutable(
                        new File(
                                "E:\\Selenium WebDriver\\chromedriver_win_23.0.1240.0\\chromedriver.exe"))
                .usingAnyFreePort().build();
        service.start();
        // 建立一個 Chrome 的瀏覽器例項
        WebDriver driver = new RemoteWebDriver(service.getUrl(),
                DesiredCapabilities.chrome());

        // 讓瀏覽器訪問 Baidu
        driver.get("http://www.baidu.com");
        // 用下面程式碼也可以實現
        // driver.navigate().to("http://www.baidu.com");

        // 獲取 網頁的 title
        System.out.println("1 Page title is: " + driver.getTitle());

        // 通過 id 找到 input 的 DOM
        WebElement element = driver.findElement(By.id("kw"));

        // 輸入關鍵字
        element.sendKeys("zTree");

        // 提交 input 所在的 form
        element.submit();

        // 通過判斷 title 內容等待搜尋頁面載入完畢,Timeout 設定10秒
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().endsWith("ztree");
            }
        });

        // 顯示搜尋結果頁面的 title
        System.out.println("2 Page title is: " + driver.getTitle());

        // 關閉瀏覽器
        driver.quit();
        // 關閉 ChromeDriver 介面
        service.stop();

    }
}

執行一下看看,是不是一切OK了?

【2012.12.06補充】

上一個 Demo 中無法正常使用 new ChromeDriver(),今天在做進一步學習時看到一篇文章(http://qa.blog.163.com/blog/static/19014700220122231779/),恍然大悟,原來只需要把 ‘webdriver.chrome.driver’ 的值設定為 chromedriver 的路徑就可以了。

package lesson1;

import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ExampleForChrome2 {
    public static void main(String[] args) throws IOException {
        // 設定 chrome 的路徑
        System.setProperty(
                "webdriver.chrome.driver",
                "E:\\Selenium WebDriver\\chromedriver_win_23.0.1240.0\\chromedriver.exe");
        // 建立一個 ChromeDriver 的介面,用於連線 Chrome
        // 建立一個 Chrome 的瀏覽器例項
        WebDriver driver = new ChromeDriver();

        // 讓瀏覽器訪問 Baidu
        driver.get("http://www.baidu.com");
        // 用下面程式碼也可以實現
        // driver.navigate().to("http://www.baidu.com");

        // 獲取 網頁的 title
        System.out.println("1 Page title is: " + driver.getTitle());

        // 通過 id 找到 input 的 DOM
        WebElement element = driver.findElement(By.id("kw"));

        // 輸入關鍵字
        element.sendKeys("zTree");

        // 提交 input 所在的 form
        element.submit();

        // 通過判斷 title 內容等待搜尋頁面載入完畢,Timeout 設定10秒
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().endsWith("ztree");
            }
        });

        // 顯示搜尋結果頁面的 title
        System.out.println("2 Page title is: " + driver.getTitle());

        // 關閉瀏覽器
        driver.quit();

        // element = driver.findElement(By.id("kw"));
        // // element.clear();
        // element.click();
        // element.clear();
        // element.sendKeys("zTree");
        // element.submit();
    }
}

【4. 測試 IE】
想逃避 IE 嗎?? 作為前端開發,IE 你是必須要面對的,衝吧!
其實你會發現, Selenium 主要也就是針對 FireFox 和 IE 來製作的,所以把 FireFox 的程式碼修改為 IE 的,那是相當的容易,只需要簡單地兩步:
1)把 ExampleForFireFox.java 另存為 ExampleForIE.java 
2)把 WebDriver driver = new FirefoxDriver(); 修改為 WebDriver driver = new InternetExplorerDriver();
3)一般大家的 IE都是預設路徑吧,所以也就不用設定 property 了

package lesson1;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ExampleForIE {
    public static void main(String[] args) {
        // 如果你的 FireFox 沒有安裝在預設目錄,那麼必須在程式中設定
        // System.setProperty("webdriver.firefox.bin", "D:\\Program Files\\Mozilla Firefox\\firefox.exe");
        // 建立一個 FireFox 的瀏覽器例項
        WebDriver driver = new InternetExplorerDriver();

        // 讓瀏覽器訪問 Baidu
        driver.get("http://www.baidu.com");
        // 用下面程式碼也可以實現
        // driver.navigate().to("http://www.baidu.com");

        // 獲取 網頁的 title
        System.out.println("1 Page title is: " + driver.getTitle());

        // 通過 id 找到 input 的 DOM
        WebElement element = driver.findElement(By.id("kw"));

        // 輸入關鍵字
        element.sendKeys("zTree");

        // 提交 input 所在的 form
        element.submit();

        // 通過判斷 title 內容等待搜尋頁面載入完畢,Timeout 設定10秒
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().endsWith("ztree");
            }
        });

        // 顯示搜尋結果頁面的 title
        System.out.println("2 Page title is: " + driver.getTitle());

        // 關閉瀏覽器
        driver.quit();
    }
}

執行一下,是不是 so easy?

入門工作完成,現在完全可以利用 java 程式碼,讓 Selenium 自動執行我們設定好的測試用例了,不過.....這僅僅是個開始。