LoginSignup
2
0

More than 1 year has passed since last update.

Elixir で WEB スクレイピング

Last updated at Posted at 2023-05-01

概要

Chromedriver を使って WEB スクレイピングします。

環境設定

事前に、Chrome と Chromedriver をインストールする必要があります。

Docker を使う場合は以下です。

Dockerfile
FROM elixir:1.14.4
  
ENV LANG C.UTF-8

WORKDIR /api

ARG CHROME_VERSION="112.0.5615.165-1"
ARG CHROMEDRIVER_VERSION="112.0.5615.49"

RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list \
    && apt-get update -qq \
    && apt-get install -y --no-install-recommends \
    google-chrome-stable=${CHROME_VERSION} \
    && mix local.hex --force \
    && mix local.rebar \
    && mix archive.install hex phx_new 1.7.2

ADD https://chromedriver.storage.googleapis.com/${CHROMEDRIVER_VERSION}/chromedriver_linux64.zip /usr/local/bin
RUN cd /usr/local/bin && unzip chromedriver_linux64.zip

Chrome と Chromedrive のバージョンを合わせる必要があるため、変数に指定しています。
https://chromedriver.chromium.org/downloads

アプリケーション設定

※アプリケーションの新規作成の仕方は省略。

mix.exs
  defp deps do
    [
      ...,
      {:hound, "~> 1.0"},
      {:floki, "~> 0.34"}
    ]

houndfloki を使います。
hound は、headless ブラウザのアクセス制御で、flokiは、HTML パーサーです。

config/config.exs
config :hound, driver: "chrome_driver"

houndからは、Chromedirver を使うように設定します。

スクレイピング実行

事前にインストール済みの chromedriver を起動しておいてください。
ポート番号はデフォルトで問題ありません。
その後、次のように hound で、セッションを開始し、ページ情報を取得してください。

iex
proc = fn ->
  url = "https://books.toscrape.com/"
  selector = "title"

  Hound.start_session(
    browser: "chrome",
    user_agent: :chrome,
    driver: %{
      chromeOptions: %{
        args: [
          "--headless",
          "--no-sandbox"
        ]
      }
    }
  )

  navigate_to(url)

  result =
    page_source()
    |> Floki.find(selector)
    |> Floki.text(sep: " ")
    |> String.replace(~r/ /, "")
    |> IO.inspect

  Hound.end_session()
end

proc.()

注意

同時に多数のセッションを接続しての評価はしていません。

2
0
0

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
2
0