LoginSignup
2
4

More than 3 years have passed since last update.

Javaでselenium導入からキャプチャ保存する

Last updated at Posted at 2020-06-18

目次

seleniumとは
目標
準備
導入手順
テストケース
テストケースの実行

seleniumとは

Seleniumとはブラウザのオートメーションツールです。
自動でブラウザを操作することでWebサイトの動作のテストなどが行うことができます。

目標

Java selenium導入、Chrome開く→Yahooニュースに遷移→キャプチャまで。

準備

Javaプロジェクトの作成

プロジェクト名「selenium」

seleniumのDL

Java selenium version3.141.59

GoogleChromeのDL

最新版

ChromedriverのDL

GooglChromeと同一バージョンのもの

JUnitのDL

Download and installからjunit.jar、hamcrest-core.jarの最新版のjarをダウンロードする。

導入手順

1.seleniumプロジェクト直下にlibフォルダとexeフォルダを作成を作成

image.png

2.ダウンロードしたselenium-java-3.141.59.zip内のlibsフォルダ内.jarファイル全てとclient-combined-3.141.59.jarを作成したlibフォルダにコピーする。

3.libフォルダにコピーしたjarファイルをクラスパスに追加する

seleniumプロジェクトのプロパティからJavaのビルドパスを追加する。
コメント 2020-06-18 102953.png
コメント 2020-06-18 103442.png

4.ダウンロードしたChromedriver.exeを作成したexeフォルダにコピーする。

これで準備完了です。

テストケース

実際に動かしていきます。
この辺を参考にすると大体動かせる。
https://qiita.com/VA_nakatsu/items/0095755dc48ad7e86e2f
https://qiita.com/mochio/items/dc9935ee607895420186

プロジェクト構成

コメント 2020-06-18 140323.png

・ChromeTest.java

メイン処理部分。
TestSetting.javaを継承している。
seleniumではJavascriptが使用可能。

package test.selenium;

import java.io.IOException;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriverException;

import util.TestUtils;

public class ChromeTest extends TestSetting {

    /**
     * テスト実行処理
     *
     * @throws WebDriverException
     * @throws IOException
     */
    @Test
    public void testChrome() throws WebDriverException, IOException{
        // キャプチャ保存フォルダを作成
        String path = TestUtils.mkdir(this.capturePath, "保存フォルダ");

        // YAHOOニュースページに遷移
        this.driver.get("https://news.yahoo.co.jp/");

        // ITニュース一覧画面へ遷移
        this.driver.findElement(By.cssSelector("#snavi > ul.yjnHeader_sub_cat > li:nth-child(7)")).click();

        // 画面をキャプチャする
        TestUtils.screenShot(this.driver, path, "スクショ");

        // 画面を下へ移動
        JavascriptExecutor js = (JavascriptExecutor) this.driver;
        js.executeScript("window.scrollBy(0,3000)");

        // 画面をキャプチャする
        TestUtils.screenShot(this.driver, path, "画面移動後");
    }
}

・TestSetting.java

テスト実行時の最初に動作し、キャプチャ保存フォルダを作成しchromeを開いてくれるとこ

package test.selenium;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import util.TestUtils;



public class TestSetting {

    // キャプチャ用ファイル配置先
    protected String capturePath;

    protected WebDriver driver;

    // テスト実行前動作
    @Before
    public void initSet() throws IOException{
        // 実行ユーザーのデスクトップパスを取得する
        String desktopPath = System.getProperty("user.home") + "\\Desktop";

        // デスクトップにキャプチャ保存フォルダを作成
        this.capturePath = TestUtils.mkdir(desktopPath, "キャプチャ保存フォルダ");

        // Chromedriveのパスを通す
        System.setProperty("webdriver.chrome.driver", "./exe/chromedriver.exe");

        // ダウンロード先を指定のフォルダに変更する
        Map<String, Object> dir = new HashMap<String, Object>();
        dir.put("download.default_directory", this.capturePath);

        ChromeOptions option = new ChromeOptions();
        option.setExperimentalOption("dir", dir);

        // chromeを起動
        this.driver = new ChromeDriver();

        // ウィンドウを最大化
        this.driver.manage().window().maximize();
    }

    // テスト実行後動作
    @After
    public void yeild() throws IOException{
        // chromeを閉じる
        this.driver.quit();
    }
}

・TestUtils.java

スクリーンショット処理とキャプチャフォルダ作成処理

package util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;

public class TestUtils {

    /**
     * 表示部分をスクリーンショット
     *
     * @param driver
     * @param path
     * @param filename
     * @throws IOException
     */
    public static void screenShot(WebDriver driver, String path, String filename) throws IOException{

        driver.manage().timeouts().implicitlyWait(30,  TimeUnit.SECONDS);
        driver.switchTo().defaultContent();
        TakesScreenshot ts = (TakesScreenshot) new Augmenter().augment(driver);
        Path from = Paths.get(ts.getScreenshotAs(OutputType.FILE).toURI());
        Path to = Paths.get(path + "\\" + filename + ".png");
        Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
    }

    /**
     * キャプチャ用のフォルダを指定の場所に作成
     *
     * @param dirpath
     * @param dirname
     * @return
     * @throws IOException
     */
    public static String mkdir(String dirpath, String dirname) throws IOException{
        String path = Paths.get(dirpath, dirname).toString();

        if(Files.notExists(Paths.get(dirpath,  dirname))) {
            Files.createDirectories(Paths.get(dirpath, dirname));
        }
        return path;
    }
}

テストケースの実行

ChromeTest.javaを「実行」->「JUnitテスト」から実行するとChromeが起動しデスクトップ上にキャプチャ保存フォルダが作られキャプチャしたものが保存される。
コメント 2020-06-18 150109.png

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4