LoginSignup
12
4

More than 3 years have passed since last update.

2019年に爆速でrocker/tidyverseにRSelenium入れてRからWebクロールしまくる件

Last updated at Posted at 2019-05-11

こんなもんさっさと出来るだろうと思ったら、案外つまづいたので手順だけまとめます。

書いてる人はMojave 10.14.4です。
なるべく各プラットフォームのパッケージマネジャをそのまま使います。

使うもの:rocker/tidyverse のコンテナ

Dockerかもん。sudoを有効に

お好みでdockerfile弄る - https://qiita.com/kazutan/items/1af4d0c4defb4de4b7fb

On_the_Mac
docker run --rm -p 8787:8787 -e PASSWORD=PASSWORD -e ROOT=TRUE rocker/tidyverse

起動したら http://localhost:8787 を開く
id: rstudio
pass: PASSWORD

こっからDocker内:RStudio まずターミナル

sudo有効になってるので、ターミナルから下記を撃ちまくる

RStudioのターミナルから 1 - apt

run_inside_container/rstudio
sudo apt-get install -y chromium chromedriver fonts-noto-cjk default-jre curl

RStudioのターミナルから 2 - Selenium stand alone server

https://www.seleniumhq.org/download/ から最新版を。
2019/5時点は "3.141.59" / selenium-server-standalone-3.141.59.jar

https://bit.ly/2TlkRyu がいつも最新版にリンクされてるらしい
一撃でダウンロードからの、乱暴に起動

getselenium
# ひっと えんど
curl -O `curl https://bit.ly/2TlkRyu | grep -Eo "(http|https)://[a-zA-Z0-9./?=_-]*"`
# らーん
java -jar selenium-server-standalone*

こっからR

2019年、pacman使わないのは犯罪となった

scrape.R
## このプロジェクト用
pacman::p_load(xml2, rvest, RSelenium)
## いつもの (load below project specifics, to avoid function masking issues)
pacman::p_load(dbplyr, tidyverse, jsonlite, lubridate, stringr, readr)

extraCapabilities設定 / ファイルの自動ダウンロードもついでに設定

scrape.R
eCaps <- list(
    chromeOptions = 
      list(
        prefs = list(  # ダウンロード時にダイアログ出さない設定
        "profile.default_content_settings.popups" = 0L,
        "download.prompt_for_download" = FALSE,
        "download.default_directory" = "~/extract_temp"
        ),
        # この'--no-sandbox'が無いとdockerコンテナごと設定変えないといけなくなる
        args = c('--no-sandbox', '--headless', '--disable-gpu', '--window-size=1200,1800')
      )
    )
scrape.R
  # 起動済みのSeleniumサーバに接続 (rsDriverで直起動も出来るはず、なんだけどなんか機能しない)
  remDr <- remoteDriver(
    remoteServerAddr = "localhost",
    port = 4444L,
    browserName = "chrome",
    extraCapabilities = eCaps)

起動すっぞ

scrape.R
remDr$open()
#こんな感じでログイン処理まとめた
win3login()

削るぞ削るぞ

scrape.R
jan_list <- get_janlist() # 欲しいぞリスト取得

# Test run - single item
item <- win3_extract_item("9784199801907")
# 1万件とか余裕だった。サーバ不可に気をつけて適度にウェイト入れる
results <- sapply(jan_list$jancode[1:10], win3_extract_item)

注意点
google-chrome入れちゃうと「古いバージョンにしろ(2019/5時点で73以下)とか言われてさまよう事になるので初めからchromiumだけ使う。
はじめて Qiita書きました。変なところあったら優しく教えてください。(びびり)

次はcronRで自動実行やります:
https://cran.r-project.org/web/packages/cronR/README.html

もちょい実用的なハウツーみたいなのも書きました:
https://qiita.com/taiyodayo/items/fca8f9185a684221a799

12
4
1

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
12
4