網頁開發上,測試是相當重要,但卻不是太容易順暢的執行。雖然 Selenium IDE 已經提供了相當好的介面,可以用錄製的方式處理,但是對於不同瀏覽器、平台等等還是不容易處理。
特別如果希望能夠有單元性的測試,要結合程式開發,就需要透過 Selenium Server + Web Driver + Remote Control。
Selenium Server 提供了 Remote Control 的介面,執行起來之後,只可以透過很多程式來控制,像是,Java、C#、Ryby、Python、JavaScripte (node) 或是 PHP 都可以,這邊主要先用 PHP 來介紹。
應用的流程架構如下

安裝 Selenium Server
到 http://www.seleniumhq.org/download/ 下載 Selenium Server。完成後會取得一個 jar 檔 (ex: selenium-server-standalone-2.52.0.jar),執行方式就是一般執行 jar 的方式
java -jar selenium-server-standalone-2.52.0.jar
安裝 php-webdriver
如果有 Composer 就可以快速安裝,如果沒有的話,用下列指令也可以快速下載使用
curl -sS https://getcomposer.org/installer | php
安裝 facebook 提供的 webdriver
php composer.phar require facebook/webdriver
撰寫測試程式
以下的範例,就是抓取網頁的標題
use Facebook\WebDriver\Remote\DesiredCapabilities; use Facebook\WebDriver\Remote\RemoteWebDriver; require_once 'vendor/autoload.php'; // This would be the url of the host running the server-standalone.jar $host = 'http://localhost:4444/wd/hub'; // this is the default // Set URL $url = 'https://snippetinfo.net'; // Launch Firefox $driver = RemoteWebDriver::create($host, DesiredCapabilities::firefox()); $driver->get($url); echo $driver->getTitle();
其他瀏覽器的 Web Driver
如果需要其他平台,跟其他瀏覽器的 Web Driver 可以到此抓取
- Chrome: https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver
- IE: https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver
- iOS: http://ios-driver.github.io/ios-driver/
- Android: http://selendroid.io/