R Selenium 설치 가이드 (Windows)

Page content

개요

  • R에서 Selenium을 설치하는 과정을 보여준다.
  • 우선 자바가 설치되어 있는지 확인한다.
  • 유투브에서 제목만 가져오는 Demo 코드를 작성한다.

자바를 모르시는 분

  • 만약 자바 설치를 해본적이 없다면 아래 코드를 순차적으로 입력한다.
install.packages("multilinguer")
library(multilinguer)
install_jdk()

# Rtools 설치 필요 
# https://cran.r-project.org/bin/windows/Rtools
write('PATH="${RTOOLS40_HOME}\\usr\\bin;${PATH}"', file = "~/.Renviron", append = TRUE)
Sys.which("make")

install.packages(c("stringr", "hash", "tau", "Sejong", "RSQLite", "devtools"),
                 type = "binary")

install.packages("remotes")
remotes::install_github("haven-jeon/KoNLP",
                        upgrade = "never",
                        INSTALL_opts = c("--no-multiarch"))

library(KoNLP)
useNIADic()
  • 마지막 코드에서 콘솔창이 보인다면 정상적으로 설치가 완료가 된 것이다.
> library(KoNLP)
Checking user defined dictionary!

> useNIADic()
Backup was just finished!
1213109 words dictionary was built.
  • 검색창에서 시스템 환경 변수 편집을 검색 후, 실제 자바가 설치가 되어 있는지 직접 확인한다.
    • 환경변수 - 시스템 변수 탭 내 Path 클릭 후 확인 버튼 - 환경 변수 편집 순차적으로 탭을 확인한다.

Untitled

  • 위 R 코드를 실행한 뒤 에러가 없다면 정상적으로 화면처럼 나타나야 한다.

자바를 설치 해보신 분

Selenium 필수 파일 다운로드

  • 우선 C 드라이브 하단에 Selenium 폴더를 생성한다. 여기에 3가지의 파일을 추가할 것이다.
    • 필자는 C드라이브 - edu - Selenium
  • 그리고 아래와 같이 3개의 파일을 추가할 것이다.

Untitled

Untitled

  • 이번에는 geckodriver를 다운로드 받는다.
  • 아래 그림에서 본인 윈도우 버전에 맞는 파일을 다운로드 받는다. 필자는 64비트이기 때문에 win64.zip 파일을 다운로드 받았다.
    • 마찬가지로 압축파일을 푼 뒤, 응용프로그램만 제거한다.

Untitled

Untitled

  • 너무 높은 버전을 선택하면 안 맞을 수 있다. 필자는 3.141 버전을 선택하였다.

Untitled

Selenium 실행하기

  • 폴더 주소창을 복사한다.

Untitled

  • 먼저 명령프롬프트를 실행한다. (검색창에서 명령프롬프트 검색)

Untitled

  • 실행 후, 아래와 같이 입력한다.
    • cd는 change directory의 약자이다.
C:\Users\your_name> cd C:\edu\Selenium
C:\edu\Selenium> 
  • 경로가 변경이 되었다면 아래와 같이 dir을 입력한다.
    • 만약 실행 화면에 필수 설치 파일이 없다면 경로 접근에 실패한 것이다. 그럼 경로를 처음부터 다시 잡아야 한다.
C:\edu\Selenium>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: 1A41-A270

 C:\edu\Selenium 디렉터리

2022-04-12  오후 10:08    <DIR>          .
2022-04-12  오후 09:59    <DIR>          ..
2022-04-12  오후 10:05        11,802,624 chromedriver.exe
2022-04-12  오후 10:08         6,142,528 geckodriver.exe
2022-04-12  오후 09:42        10,649,948 selenium-server-standalone-3.141.59.jar
               3개 파일          28,595,100 바이트
               2개 디렉터리  384,804,147,200 바이트 남음
  • 이제 마지막으로 아래 코드를 입력한다.
java -Dwebdriver.gecko.driver="geckodriver.exe" -jar selenium-server-standalone-3.141.59.jar -port 4445
  • 입력하면, 아래와 같이 터미널이 변경되는 것을 확인할 수 있다.
C:\edu\Selenium>java -Dwebdriver.gecko.driver="geckodriver.exe" -jar selenium-server-standalone-3.141.59.jar -port 4445
22:25:25.141 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
22:25:25.212 INFO [GridLauncherV3.lambda$buildLaunchers$3] - Launching a standalone Selenium Server on port 4445
2022-04-12 22:25:25.352:INFO::main: Logging initialized @2704ms to org.seleniumhq.jetty9.util.log.StdErrLog
22:25:25.582 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet
22:25:25.783 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 4445

R Demo

  • 유투브에서 제목을 가져오는 코드를 작성한다. (전체코드는 아래와 같다)
library(RSelenium)
library(keyring)
library(rvest)
library(magrittr)

# Start Selenium Session
remDr <- remoteDriver(
  port = 4445L,
  browserName = "chrome"
)

remDr$open()

title <- "손흥민"

remDr$navigate(paste0(remDr$navigate(paste0("https://www.youtube.com/results?search_query=", title))))
html <- remDr$getPageSource()[[1]]
html <- read_html(html)
youtube_title <- html %>% html_nodes("#video-title") %>% html_text()
youtube_title[1:20]

# End Selenium Session
remDr$close()

# End of Document
  • 우선 아래코드만 범위를 지정하여 실행하면 자동으로 새로운 크롬이 열리고 유투브에서 손흥민이 검색되는 것을 확인할 수 있다.
    • 손흥민 대신, 다른 키워드를 추가해도 된다.
library(RSelenium)
library(keyring)
library(rvest)
library(magrittr)

# Start Selenium Session
remDr <- remoteDriver(
  port = 4445L,
  browserName = "chrome"
)

remDr$open()

title <- "손흥민"

remDr$navigate(paste0(remDr$navigate(paste0("https://www.youtube.com/results?search_query=", title))))
html <- remDr$getPageSource()[[1]]
html <- read_html(html)

Untitled

  • 제목만 가져오는 코드를 작성한다.
    • 실제 화면과 동일하게 제목만 가져오는 것을 확인한다.
youtube_title <- html %>% html_nodes("#video-title") %>% html_text()
youtube_title[1:20]

Untitled

  • 마지막 코드는 Selenium을 종료하는 코드이다.