💻️
スクレイピングとサーバー実行のサンプルコード(Elixir)

ElixirでスクレイピングとWebサーバーを開発する手順を書いていきます。

開発の手順

環境構築

# 開発環境構築
$ brew install erlang
$ brew install elixir

# パッケージマネージャーのインストール
$ mix local.hex

# プロジェクトのディレクトリ作成
$ mix new scraping_server
$ cd scraping_server

$ mix new scraping_server のコマンド実行後に作成された mix.exs ファイルを開きます。

外部パッケージのインストールのために、ファイル内の defp deps do 〜 end の箇所を以下のように記述します。

defp deps do
  [
    {:plug_cowboy, "~> 2.5"},  # Webサーバー フレームワーク
    {:httpoison, "~> 1.8"},    # HTTPリクエスト用
    {:floki, "~> 0.30.0"},     # HTMLパース用
    {:poison, "~> 5.0"}        # JSONライブラリ
  ]
end

ファイルに上記を記述したら、以下コマンドを実行してパッケージをインストールします。

$ mix deps.get

インストールしている外部パッケージは以下のものです。

Webサーバーの起動

まず以下の内容で main.exs を作成します。

defmodule ScrapingServer do
  def main() do
    Plug.Cowboy.http(ScrapingServer.Plug, [], port: 3000)
  end
end

defmodule ScrapingServer.Plug do
  import Plug.Conn

  def init(options), do: options

  def call(conn, _opts) do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(200, "test")
  end
end

その後、以下コマンドを実行して http://localhost:3000 にブラウザでアクセスすると、”test” の文字が表示されます。

$ mix run -e 'ScrapingServer.main' --no-halt これで、Webサーバーの起動ができました。

スクレイピングで取得した情報を表示する

scraping_server.ex に以下の実装を追加します。

defmodule ScrapingServer do
  def main() do
    Plug.Cowboy.http(ScrapingServer.Plug, [], port: 3000)
  end
end

defmodule ScrapingServer.Plug do
  import Plug.Conn

  def init(options), do: options

  def call(conn, _opts) do
    # スクレイピング用の関数を呼び出す
    items = ScrapingServer.Scraping.run()
    items_json = Poison.encode!(items)

    conn
      |> put_resp_content_type("application/json")
      |> send_resp(200, items_json)
  end
end

# スクレイピング用の処理を追加
defmodule ScrapingServer.Scraping do
  def run() do
    url = "https://en.wikipedia.org/wiki/List_of_programming_languages"
    body = HTTPoison.get!(url).body
    Floki.find(body, ".div-col li")
      |> Enum.map(&(&1 |> Floki.text() |> String.strip()))
  end
end

追加実装の後、 $ mix run -e ‘ScrapingServer.main’ –no-halt を再実行して http://localhost:3000 にアクセスすると、 Wikipediaのページから取得したプログラミング言語一覧の文字が表示されるようになります。