トップ 言語 Java ライブラリ/Framework Selenium

Selenium Java―WebElementなど使い方とサンプル

Seleniumはブラウザの操作が可能なライブラリです。この記事ではWebElementなど使い方とサンプルなど、Java版のSeleniumについてまとめています。

▲記事トップへ

目次

このページの目次です。

1. Seleniumとは
2. Selenium WebDriver
3. Selenium Javaの簡単なサンプル
4. Selenium JavaのFirefoxDriverの使い方
5. Selenium JavaのWebElement

もっと知識を広げるための参考
更新履歴

1. Seleniumとは

Seleniumとは、Webアプリケーションの機能テストや結合テストの自動化を実現するブラウザ駆動型のテストツール群です。 Webアプリケーションのテスト自動化に特化したさまざまな機能を備えています。

2. Selenium WebDriver

Selenium WebDriverは、Webブラウザを操作するAPIを提供するライブラリです。 Selenium WebDriverは、Selenium Remote Control+WebDriverというツールになります。

Seleniumではいくつかのコンポーネントが提供されていますが、この記事ではWebDriverについてまとめています。 JUnitで記述してJenkinsで動かして、レポートをグラフ表示するなどいろいろ使い道があっていいです。

なお、前提としてJavaの基礎知識とEclipseやmavenなど開発ツールの知識が必要になります。

3. Selenium Javaの簡単なサンプル

Selenium Javaでページを表示する例です。

Javaソース(App.java)

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class App {
	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		driver.get("https://www.zealseeds.com/index.html");
	}
}

依存ライブラリ(pom.xml)

<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>com.zealseeds</groupId>
	<artifactId>App</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>

		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>2.45.0</version>
		</dependency>

	</dependencies>
</project>

サンプルの実行

Eclipseでプロジェクトを選択してCtrl+F11と実行します。 Firefoxを起動して、https://www.zealseeds.com/index.htmlのページが表示されます。

4. Selenium JavaのFirefoxDriverの使い方

上述のサンプルでは、FirefoxDriverを使用しています。 Selenium JavaのFirefoxDriverについて見ていきます。

FirefoxDriverのgetメソッド

FirefoxDriverのgetメソッドについてまとめています。

FirefoxDriverのgetメソッドのサンプルコード

Selenium JavaでFirefox起動するサンプルを紹介します。

Javaソース(App.java)

package com.zealseeds;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class App {

	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		driver.get("https://www.google.co.jp");
	}
}

依存ライブラリ(pom.xml)

<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>com.zealseeds</groupId>
	<artifactId>App</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>

		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>2.45.0</version>
		</dependency>

	</dependencies>
</project>

サンプルの実行

Eclipseでプロジェクトを選択してCtrl+F11と実行します。 Firefoxを起動して、Googleの検索ページがロードされます。

5. Selenium JavaのWebElement

取得したページのデータはWebElementというオブジェクトに格納されます。 ここではSelenium JavaのWebElementについて見ていきます。

findElement()メソッド

WebElementのfindElementメソッドを使用してHTMLの要素を操作することができます。 要素がない場合ランタイム例がをスローします。

Googleで地域設定を行って検索するサンプル

FirefoxDriverを使用してGoogleで地域設定を行って検索するサンプルです。

Javaソース(App.java)

package com.zealseeds;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class App {

	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		LocationSearch locSearch = new LocationSearch();
		locSearch.setLocation(driver, "東京都杉並区");
		locSearch.searchQuestion(driver,"区役所");
	}
}

Javaソース(LocationSearch.java)

package com.zealseeds;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class LocationSearch {

	public void setLocation(WebDriver driver, String location) {
		driver.get("https://www.google.co.jp/preferences?hl=ja#location");
		WebElement luulBox = driver.findElement(By.name("luul"));
		luulBox.sendKeys(location);
		luulBox.submit();
	}

	public void searchQuestion(WebDriver driver, String question) {
		driver.get("https://www.google.co.jp");
		WebElement searchBox = driver.findElement(By.name("q"));
		searchBox.sendKeys(question);
		searchBox.submit();
	}
}

依存ライブラリ(pom.xml)

<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>com.zealseeds</groupId>
	<artifactId>App</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>

		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>2.45.0</version>
		</dependency>

	</dependencies>
</project>

サンプルの実行

Eclipseでプロジェクトを選択してCtrl+F11と実行します。 Firefoxを起動して、Googleの地域設定で「東京都杉並区」を設定し、Googleの検索ページをロードして「区役所」で検索を行います。

Googleで地域設定を行って検索順位を取得するサンプル

FirefoxDriverを使用してGoogleで地域設定を行って検索順位を取得するサンプルです。

Javaソース(App.java)

package com.zealseeds;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class App {

	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		LocationSearch locSearch = new LocationSearch(driver);
		locSearch.setLocation("東京都練馬区");
		locSearch.searchQuestion("区役所");
		System.out.println("順位は "
		+ locSearch.getSearchRank("http://www.city.nerima.tokyo.jp/", 2)
		+ " 位です!");
		driver.quit();
	}
}

Javaソース(LocationSearch.java)

package com.zealseeds;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Navigation;
import org.openqa.selenium.WebElement;

public class LocationSearch {

	private WebDriver driver;

	private Map<String, Integer> urlRankMap;

	public LocationSearch(WebDriver settingDriver) {
		driver = settingDriver;
		urlRankMap = new HashMap<>();
	}

	public void setLocation(String location) {
		driver.get("https://www.google.co.jp/preferences?hl=ja#location");
		Navigation nav = driver.navigate();
		nav.refresh();
		WebElement luulBox = driver.findElement(By.name("luul"));
		luulBox.sendKeys(location);
		luulBox.submit();
		Alert alert = driver.switchTo().alert();
		alert.accept();
	}

	public void searchQuestion(String question) {
		driver.get("https://www.google.co.jp");
		Navigation nav = driver.navigate();
		nav.refresh();
		WebElement searchBox = driver.findElement(By.name("q"));
		searchBox.sendKeys(question);
		searchBox.submit();
	}

	public int getSearchRank(String url, int pageLimit) {

		for (int i = 0; i < pageLimit; i++) {
			getPageRanking(i * 10);
			setNextPage();
		}

		return urlRankMap.get(url);
	}

	private void getPageRanking(int start) {
		Navigation nav = driver.navigate();
		nav.refresh();
		List<String> urlInfo = new ArrayList<>();
		List<WebElement> srgs = driver.findElements(By.className("srg"));

		for (WebElement srg : srgs) {
			for (WebElement g : srg.findElements(By.className("g"))) {
					WebElement a = g.findElement(By.tagName("a"));
					urlInfo.add(a.getAttribute("href"));
			}
		}

		for (int i = 0; i < urlInfo.size(); i++) {
			System.out.println((i + 1 + start) + "位:" + urlInfo.get(i));

			if (!urlRankMap.containsKey(urlInfo)) {
				urlRankMap.put(urlInfo.get(i), i + 1 + start);
			}
		}
	}

	private void setNextPage() {
		Navigation nav = driver.navigate();
		nav.refresh();
		WebElement pnnext = driver.findElement(By.id("pnnext"));
		pnnext.click();
	}
}

依存ライブラリ(pom.xml)

<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>com.zealseeds</groupId>
	<artifactId>App</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>

		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>2.45.0</version>
		</dependency>

	</dependencies>
</project>

サンプルの実行

Eclipseでプロジェクトを選択してCtrl+F11と実行します。 Firefoxを起動して、Googleの地域設定で「東京都練馬区」を設定し、Googleの検索ページをロードして「区役所」で検索を行い、 地域設定を行った場合の練馬区公式ホームページの順位を表示します。

試しに行った時は以下の出力になりました。

1位:http://www.city.nerima.tokyo.jp/
2位:http://ja.wikipedia.org/wiki/%E6%9D%B1%E4%BA%AC%E9%83%BD%E5%8C%BA%E9%83%A8
3位:http://www.city.setagaya.lg.jp/
4位:http://www.metro.tokyo.jp/PROFILE/map_to.htm
5位:http://www.city.shinjuku.lg.jp/
6位:http://www.city.toshima.lg.jp/
7位:http://www.city.yokohama.lg.jp/aoba/
8位:https://www.city.shibuya.tokyo.jp/
9位:http://www.city.shinagawa.tokyo.jp/
10位:http://www.city.chuo.lg.jp/
11位:http://www.city.minato.tokyo.jp/
12位:http://www.city.ota.tokyo.jp/
13位:http://www.city.adachi.tokyo.jp/
14位:http://www.city.itabashi.tokyo.jp/
15位:http://www.city.koto.lg.jp/
16位:http://www.city.meguro.tokyo.jp/
17位:http://www.city.suginami.tokyo.jp/
18位:http://www.city.edogawa.tokyo.jp/
19位:http://www.city.tokyo-nakano.lg.jp/
20位:http://www.city.katsushika.lg.jp/
順位は 1 位です!

もっと知識を広げるための参考

更新履歴

戻る

スポンサーリンク

サイト内のページ

言語
C・C++ /HTML /Java /JavaScript /PHP /シェルスクリプト

開発環境
Ant /Burp /Eclipse /Fiddler /gcc /gdb /Git /g++ /JDK /JMeter /JUnit /Teraterm /ZAP

技術・仕様
Ajax /CORBA /Jakarta EE(旧称J2EE、Java EE) /JNI

ライブラリ/Framework/CMS
bootstrap /jQuery /FuelPHP /Lucene /MyBatis /Seasar2 /Spring /Struts /WordPress

Web API
Google Maps

ITインフラOSとミドルウェア
Linux /Windows /シェル
ActiveMQ /Tomcat /MariaDB /MySQL /Nagios /Redis /Solr

ITインフラサーバー
公開Webサーバー

ITインフラネットワーク
プログラミング /構築

ITインフラセキュリティ
公開サーバーのセキュリティ

PC製品
ZOTAC

SI
ホームページの作り方

その他
IT用語 /ITスキル体系

スポンサーリンク

関連サイト内検索ツール

zealseedsおよび関連サイト内のページが検索できます。

IPアドレス確認ツール

あなたのグローバルIPアドレスは以下です。

3.14.70.203

HTMLの表示色確認ツール

パスワード生成ツール

文字数のプルダウンを選択して、取得ボタンを押すと「a~z、A~Z、0~9」の文字を ランダムに組み合わせた文字列が表示されます。

ここに生成されます。

スポンサーリンク