概要
SeleniumはWebアプリケーションのテストツールであり、ブラウザでのボタンクリックなどを自動化できる。
しかし、Seleniumでのテスト実行時はブラウザが表示されるので、人間がSelenium実行中のマシンで別の操作をするとテストを妨げてしまう場合がある。
一方、SeleniumでGhost Driverを利用すると、ブラウザが表示されないので前述の理由でテストを妨げることはない。
また、ブラウザが表示されないことで実行時間を短くできる利点もある。
そこで、本記事では、Ghost Driverを身近なOSであるWindowsで手短に体験するための環境準備とテストファイル実行方法を紹介する。
環境準備
動作確認バージョン
・Windows7 HomePremium
・JDK 1.8.0_151
・Selenium Standalone Server 3.8.1
・PhantomJS 2.1.1
・Ghost Driver 1.2.1
※Selenium公式サイトにリンクが掲載されているGhostDriverのバージョンは1.2.0だが、今回は1.2.1を使用する。
インストール方法
JDK
以下記事のとおりインストールする。
WindowsへのJDKインストール方法
Selenium Standalone Server
1.Selenium公式サイトからselenium-server-standalone-3.8.1.jarをダウンロードする。
2.任意のフォルダに展開する。
今回は、Cドライブ直下にselenium-server-standalone-3.8.1という名前のフォルダを作成し、その中に展開する。
PhantomJS
1.PhantomJSの公式サイトにアクセスし、phantomjs-2.1.1-windows.zipをダウンロードする。
2.ダウンロードしたphantomjs-2.1.1-windows.zipを任意のフォルダに展開する。
今回は、Cドライブ直下にphantomjs-2.1.1という名前のフォルダを作成し、その中に展開する。
Ghost Driver
1.http://grepcode.com/snapshot/repo1.maven.org/maven2/com.codeborne/phantomjsdriver/1.2.1にアクセスする。
2.phantomjsdriver-1.2.1.jarをダウンロードし、任意のフォルダに展開する。
3.展開した中身のorg\openqa\selenium\phantomjsフォルダをコピーする。
4.コピーしたphantomjsフォルダをC:\selenium-server-standalone-3.8.1\org\openqa\seleniumフォルダ内にペーストする。
サンプルファイルの作成、実行
サンプルファイルの作成
以下ファイルをC:\selenium-server-standalone-3.8.1フォルダに作成する。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
public class GhostDriverTest {
public static void main(String[] args) {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"C:\\\\phantomjs-2.1.1\\bin\\phantomjs.exe"
);
WebDriver driver = new PhantomJSDriver(caps);
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!");
element.submit();
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
サンプルファイルの実行
1.コマンドプロンプトを開き以下のとおり入力する。
C:\selenium-server-standalone-3.8.1>javac GhostDriverTest.java
C:\selenium-server-standalone-3.8.1>java GhostDriverTest
2.コマンドプロンプトに以下メッセージが表示されるのを確認する。
※セッション情報なども表示される。
Page title is: Cheese! - Google 検索