Selenium을 사용해 보면 의외로 쉽게 시작할 수 있었다
최근, Selenium을 조사할 기회가 있어 「어라? 이것 곧 시작할 수 있잖아?」라고 생각해 보았습니다.
요약
ChromeDriver도 포함되어 있으므로 Chrome 버전이 맞으면 이대로 실행할 수 있어야합니다.
전제
환경
조건
셀레늄
Selenium WebDriver(Selenium2)
실행 기계
macOS High Sierra(10.13.5)
브라우저
Google 크롬 (67.0.3396.87)
프로그램 언어
자바
테스트 프레임워크
JUnit
빌드 도구
maven
※Selenium-Server는 사용하지 않는다. (로컬 PC를 사용하여 Chrome에서 테스트하기 때문에)
준비
Selenium Client 다운로드
Selenium을 실행하기위한 라이브러리

Selenium Client 다운로드
Selenium을 실행하기위한 라이브러리

ChromeDriver 다운로드
Selenium에서 브라우저를 제어하거나 브라우저 상태를 검색하는 도구

브라우저마다 대응 Driver가 있어, 이번은 Chrome에서 확인했다
다운로드 사이트 사이트에서 사용하는 Chrome 버전에 맞는 드라이버를 다운로드합니다.
ChromeDriver wiki
Maven 프로젝트 만들기

Selenium을 움직여 보았습니다.
공식 사이트에서 Selenium WebDriver을 기반으로 Google 검색을 실행합니다.Thread.sleep(1000)
는 Qiita에 붙일 이미지를 캡처하기위한 Wait 용입니다.
SeleniumExample.javapackage selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniumExample {
public static void main(String[] args) throws InterruptedException {
// ChromeDriverまでのパスを設定する
System.setProperty("webdriver.chrome.driver", "selenium/chromedriver/2.40/chromedriver");
// Chromeドライバーインスタンスを作成する
WebDriver driver = new ChromeDriver();
// Google.comにアクセスする
driver.get("https://www.google.com");
// 表示しているページのTitleを出力する
System.out.println("Page title is: " + driver.getTitle());
Thread.sleep(1000);
// 検索ワード入力エレメントに、検索ワードを渡して、submitする
WebElement searchElement = driver.findElement(By.name("q"));
searchElement.sendKeys("Cheese!");
Thread.sleep(1000);
searchElement.submit();
// ページが更新するまで待つ(Timeoutは10秒)
new WebDriverWait(driver, 10)
.until((ExpectedCondition<Boolean>) webDriver -> webDriver.getTitle().toLowerCase().startsWith("cheese!"));
// ページ更新後のTitleを出力する
System.out.println("Page title is: " + driver.getTitle());
Thread.sleep(1000);
// ブラウザーを閉じる
driver.quit();
}
}
실행하면 Chrome이 일어나서 검색을 실행하고 콘솔에는 검색 전후의 Title이 출력되었으므로 Selenium에서 브라우저를 제어하여 정보를 얻을 수 있음을 확인할 수 있었다.

(Chrome이 자동으로 활성화되지 않으므로 직접 Chrome으로 전환)
다음으로 ChromeDriver 사이트 Getting started의 Controlling ChromeDriver's lifetime을 바탕으로 JUnit에서 테스트 케이스를 작성해 보았습니다.
(공식 샘플의 Selenium-Server의 정의 부분은 삭제하고 있습니다)
ChromeTest.javapackage selenium;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ChromeTest {
private WebDriver webDriver;
@Before
public void createDriver() {
System.setProperty("webdriver.chrome.driver", "selenium/chromedriver/2.40/chromedriver");
webDriver = new ChromeDriver();
}
@After
public void quitDriver() {
webDriver.close();
}
@Test
public void testGoogle() {
webDriver.get("https://www.google.com");
assertThat(webDriver.getTitle(), is("Google"));
}
@Test
public void testGoogleSearch() {
webDriver.get("https://www.google.com");
WebElement searchElement = webDriver.findElement(By.name("q"));
searchElement.sendKeys("selenium");
searchElement.submit();
// ページが更新するまで待つ(Timeoutは10秒)
new WebDriverWait(webDriver, 10)
.until((ExpectedCondition<Boolean>) webDriver -> webDriver.getTitle().toLowerCase().startsWith("selenium"));
assertThat(webDriver.getTitle(), is("selenium"));
}
}

testGoogleSearch 메소드가 실패했습니다.
title이 예상대로는 아니었기 때문에 assertThat(webDriver.getTitle(), is("selenium"));
를 assertThat(webDriver.getTitle(), is("selenium - Google 検索"));
로 바꾸고 다시 실행합니다.

안전하고 성공했습니다.
요약
Selenium client와 Driver를 사용하면 비교적 쉽게 브라우저를 사용한 테스트 코드를 작성할 수 있습니다.
실제로는 CI 툴과 연계한다. Selenium-Server를 도입하거나, 멀티 브라우저에도 대응하는 것, 테스트 코드를 가능한 한 간단하게 준비하는 방법 등을 검토할 필요가 있습니다만, 조금씩 진행해 나가고 싶습니다.
Reference
이 문제에 관하여(Selenium을 사용해 보면 의외로 쉽게 시작할 수 있었다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/kazokmr/items/0dc6b67e5a90ffc27db6
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniumExample {
public static void main(String[] args) throws InterruptedException {
// ChromeDriverまでのパスを設定する
System.setProperty("webdriver.chrome.driver", "selenium/chromedriver/2.40/chromedriver");
// Chromeドライバーインスタンスを作成する
WebDriver driver = new ChromeDriver();
// Google.comにアクセスする
driver.get("https://www.google.com");
// 表示しているページのTitleを出力する
System.out.println("Page title is: " + driver.getTitle());
Thread.sleep(1000);
// 検索ワード入力エレメントに、検索ワードを渡して、submitする
WebElement searchElement = driver.findElement(By.name("q"));
searchElement.sendKeys("Cheese!");
Thread.sleep(1000);
searchElement.submit();
// ページが更新するまで待つ(Timeoutは10秒)
new WebDriverWait(driver, 10)
.until((ExpectedCondition<Boolean>) webDriver -> webDriver.getTitle().toLowerCase().startsWith("cheese!"));
// ページ更新後のTitleを出力する
System.out.println("Page title is: " + driver.getTitle());
Thread.sleep(1000);
// ブラウザーを閉じる
driver.quit();
}
}
package selenium;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ChromeTest {
private WebDriver webDriver;
@Before
public void createDriver() {
System.setProperty("webdriver.chrome.driver", "selenium/chromedriver/2.40/chromedriver");
webDriver = new ChromeDriver();
}
@After
public void quitDriver() {
webDriver.close();
}
@Test
public void testGoogle() {
webDriver.get("https://www.google.com");
assertThat(webDriver.getTitle(), is("Google"));
}
@Test
public void testGoogleSearch() {
webDriver.get("https://www.google.com");
WebElement searchElement = webDriver.findElement(By.name("q"));
searchElement.sendKeys("selenium");
searchElement.submit();
// ページが更新するまで待つ(Timeoutは10秒)
new WebDriverWait(webDriver, 10)
.until((ExpectedCondition<Boolean>) webDriver -> webDriver.getTitle().toLowerCase().startsWith("selenium"));
assertThat(webDriver.getTitle(), is("selenium"));
}
}
Selenium client와 Driver를 사용하면 비교적 쉽게 브라우저를 사용한 테스트 코드를 작성할 수 있습니다.
실제로는 CI 툴과 연계한다. Selenium-Server를 도입하거나, 멀티 브라우저에도 대응하는 것, 테스트 코드를 가능한 한 간단하게 준비하는 방법 등을 검토할 필요가 있습니다만, 조금씩 진행해 나가고 싶습니다.
Reference
이 문제에 관하여(Selenium을 사용해 보면 의외로 쉽게 시작할 수 있었다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/kazokmr/items/0dc6b67e5a90ffc27db6텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)