Seleium2.0の全体像の説明はWebDriver - あすかぜ・ねっとが参考になります。
しかし、実際に動かしてみないとピンと来ないのでGettingStarted - selenium - Getting started with WebDriver - Browser automation framework - Google Project Hostingに従って、Selenuim2.0を動かしてみましょう。
ダウンロードする
- 今は2.4が最新
- 好きな場所に解凍する
プロジェクトの参照ライブラリにダウンロードしたjarを追加する
ソースを追加
package org.openqa.selenium.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; public class Example { public static void main(String[] args) { // HtmlUnitのインスタンスを生成します。 // 続くコードは実装ではなくインタフェースに依存します。 WebDriver driver = new HtmlUnitDriver(); // Googleを訪問します。 driver.get("http://www.google.com"); // Inpu要素を名前で検索します。 WebElement element = driver.findElement(By.name("q")); // 検索キーワードを入力 element.sendKeys("Cheese!"); // Submitします。WebDriverが自動的にFormを見つけます。 element.submit(); // ページタイトルを確認します。 System.out.println("Page title is: " + driver.getTitle()); } }
実行する
FirefoxDriverに変えて実行してみる
package org.openqa.selenium.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class Example { public static void main(String[] args) { // インスタンス化するクラスをFirefoxDriverに変更します。 WebDriver driver = new FirefoxDriver(); 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()); } }
分かったこと
ブラウザを操作するコードをJavaで書けることがわかりました。ここまでなら「Oleでいいじゃん」て話です。
あとは検索条件を指定する抽象クラスByの名前がかっこいいですね。