memostack
article thumbnail
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
반응형

목표

Java와 Selenium을 가지고 웹 크롤러를 만든다.

 

환경

  • Maven 기반의 Java 프로젝트
  • Java 버전 OpenJDK 1.8.0_242

 

Selenium 라이브러리

편의를 위해 Maven 프로젝트로 생성했다. Selenium 라이브러리를 가져온다.

mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java

 

Maven Repository: org.seleniumhq.selenium » selenium-java

Selenium automates browsers. That's it! What you do with that power is entirely up to you. VersionRepositoryUsagesDate4.0.x4.0.0-alpha-6Central4May, 20204.0.0-alpha-5Central5Mar, 20204.0.0-alpha-4Central7Jan, 20204.0.0-alpha-3Central12Sep, 20194.0.0-alpha-

mvnrepository.com

본 글에서는 3.141.59 버전을 사용한다.

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>3.141.59</version>
</dependency>

 

Chrome Driver 다운로드

selenium 버전에서는 Chrome Driver로 86버전을 사용해야한다.

chromedriver.storage.googleapis.com/index.html?path=86.0.4240.22/

 

https://chromedriver.storage.googleapis.com/index.html?path=86.0.4240.22/

 

chromedriver.storage.googleapis.com

85버전도 가능하긴 하지만, 경고 메세지가 뜬다.

84버전 이하부터는 사용할 수 없고 아래와 같이 오류가 발생한다.

Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 84
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
...중략...
Driver info: driver.version: ChromeDriver
...중략...

 

Java 코드

크롬 드라이버를 가지고 오는 방법에는 2가지 방법이 있다.

  1. JVM 시스템 속성에 드라이버의 경로를 넣는방법
  2. ChromeDriverService를 이용하는 방법

 

System property 사용

// 드라이버 경로
final File driverFile = new File("chromedriver 바이너리 경로");
final String driverFilePath = driverFile.getAbsolutePath();

// 시스템 property 설정
System.setProperty("webdriver.chrome.driver", driverFilePath);

// driver 객체 생성
final WebDriver driver = new ChromeDriver();

 

ChromeDriverService 사용

// 드라이버 경로 설정
final File driverFile = new File("chromedriver 바이너리 경로");
final String driverFilePath = driverFile.getAbsolutePath();

// ChromeDriverService 서비스 객체 생성
final ChromeDriverService service;
service = new ChromeDriverService.Builder()
        .usingDriverExecutable(driverFile)
        .usingAnyFreePort()
        .build();
try {
    service.start();
} catch (IOException e) {
    e.printStackTrace();
}

// 드라이버 객체 생성
final WebDriver driver = new ChromeDriver(service);

 

아래 코드는 구글에 cheese를 검색하고, 더보기 버튼의 텍스트를 가져오는 코드이다.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) {
        // 크롬 드라이버를 가지고 옴
        final File driverFile = new File("src/main/resources/bin/chromedriver_v86.exe");
        final String driverFilePath = driverFile.getAbsolutePath();
        if(!driverFile.exists() && driverFile.isFile()) {
            throw new RuntimeException("Not found file. or this is not file. <" + driverFilePath + ">");
        }

        // 방법 1. 시스템 프로퍼티 설정 (JVM이 시작할때 자동으로 설정되는 시스템 속성 값)
//        System.setProperty("webdriver.chrome.driver", driverFilePath);
//        final WebDriver driver = new ChromeDriver();

        // 방법 2. ChromeDriverService를 생성해서 사용
        final ChromeDriverService service;
        service = new ChromeDriverService.Builder()
                .usingDriverExecutable(driverFile)
                .usingAnyFreePort()
                .build();
        try {
            service.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        final WebDriver driver = new ChromeDriver(service);
        final WebDriverWait wait = new WebDriverWait(driver, 10);
        
        // 크롤링 시작
        try {
            driver.get("https://google.com/ncr");
            Thread.sleep(5000);  // Let the user actually see something!
            driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);
            final WebElement firstResult = wait.until(presenceOfElementLocated(By.cssSelector("h3>div")));
            System.out.println(firstResult.getAttribute("textContent"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 프로그램이 종료되면 resource 해제
            driver.quit();
            service.stop();
        }
    }
}
// 결과값
Show more

 

Reference

sites.google.com/a/chromium.org/chromedriver/getting-started

 

Getting started - ChromeDriver - WebDriver for Chrome

WebDriver for Chrome

sites.google.com

 

반응형
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
profile

memostack

@bluemiv_mm

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!