📌
Chrome + Selenium + Ruby によるスクレイピング環境を Docker で構築する
はじめに
- Dockerfile 内で Chrome と ChromeDriver をインストールする方法
- Ruby で Selenium によるスクレイピングを行う際の
selenimu-webdriver
の設定
を紹介します。
Dockerfile の作成
Selenium を動かすためのブラウザ(Chrome)とドライバー(ChromeDriver)をインストールします。
FROM ruby:3.1
# Chrome のインストール
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add \
&& echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | tee /etc/apt/sources.list.d/google-chrome.list \
&& apt-get update -qq \
&& apt-get install -y google-chrome-stable libnss3 libgconf-2-4
# ChromeDriver のインストール
# 現在の最新のバージョンを取得し、それをインストールする。
RUN CHROMEDRIVER_VERSION=`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE` \
&& curl -sS -o /tmp/chromedriver_linux64.zip http://chromedriver.storage.googleapis.com/$CHROMEDRIVER_VERSION/chromedriver_linux64.zip \
&& unzip /tmp/chromedriver_linux64.zip \
&& mv chromedriver /usr/local/bin/
WORKDIR /app
COPY Gemfile /app
COPY Gemfile.lock /app
RUN bundle install
COPY . /app
CMD ["bundle", "exec", "ruby", "xxxx.rb"]
Ruby のサンプルコード
Yahoo Japan のサイトからh1タグのテキストを取ってくるコード。
require 'selenium-webdriver'
options = Selenium::WebDriver::Chrome::Options.new
# 下記オプションをつけないと Docker 上で動かない。
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = Selenium::WebDriver.for :chrome, options: options
driver.navigate.to 'https://www.yahoo.co.jp/'
h1 = driver.find_element(:css, 'h1')
puts h1.text
driver.quit
Discussion