参考にさせて頂いたページ
簡単・便利、ブラウザの自動操作!~Selenium WebDriver~ : アシアルブログ
サンプルソース
前回までに作成したHogeTest.javaを以下のように書き換えた
package com.example.tests;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.junit.*;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HogeTest {
private WebDriver driver;
@Before
public void setUp(){
// Firefoxを起動する
// driver = new FirefoxDriver();
// Chromeを起動する
System.setProperty("webdriver.chrome.driver","./driver/chromedriver.exe");
driver = new ChromeDriver();
// IEを起動する
// System.setProperty("webdriver.ie.driver", "./driver/IEDriverServer.exe");
// driver = new InternetExplorerDriver();
}
@Test
public void testSample(){
String[][] params;
// キャプチャを取得したいページ数
params = new String[3][];//params[0],params[1],params[2],の3つの配列を用意する
String[] param;
//params[0]の設定
param = new String[2];
param[0] = "https://www.google.co.jp/";
param[1] = generateFileName(param[0]);
params[0] = param;
//params[1]の設定
param = new String[2];
param[0] = "http://www.yahoo.co.jp/";
param[1] = generateFileName(param[0]);
params[1] = param;
//params[2]の設定
param = new String[2];
param[0] = "http://blog.asial.co.jp/1180";
param[1] = generateFileName(param[0]);
params[2] = param;
try {
for (int i = 0; i < params.length; i++) {
String[] option = params[i];
capture(option[0], option[1]);
}
} catch (WebDriverException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}//end of @Test
@After
public void tearDown(){
//ブラウザを閉じる
driver.quit();
}
public void capture(String url, String filename) throws Exception{
driver.get(url);
FileUtils.copyFile(
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE),
new File(filename)
);
}
public static String generateFileName(String str1){
String regex1 = "(http[s]*://[a-z]*.[a-z]*.[a-z]*.[a-z]*/)";
Pattern p1 = Pattern.compile(regex1);
Matcher m1 = p1.matcher(str1);
String str2 = m1.replaceAll("");
String regex2 = "(/)";
Pattern p2 = Pattern.compile(regex2);
Matcher m2 = p2.matcher(str2);
String str3 = m2.replaceAll("__");
return str3+".png";
}
}
取得した画像の保存場所
例えば参考ページにそのままならって相対パスで、
FileUtils.copyFile(
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE),
new File("./hogehoge.png"));
のように記述した場合、
C:\Users\ユーザー名\workspace\SeleniumSample\hogehoge.png
に保存される。