LoginSignup
4
1

More than 5 years have passed since last update.

clojureでスクレイピングする

Posted at

使用するライブラリ

http-kitはhttpクライアントとして使います。
enliveはhtmlをparseするのに使います。

プロジェクトにライブラリを追加

dependenciesにライブラリを追加してインストールします。

project.clj
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [enlive "1.1.6"]
                 [http-kit "2.3.0"]]

そしてライブラリをrequireします。

core.clj
(ns foo.core
  (:gen-class)
  (:require [net.cgrand.enlive-html :as html]
            [org.httpkit.client :as http]))

http-kitでhttpリクエスト

http-kitではリーダーマクロの@を使うことでリクエストを同期的に扱うことができます。
レスポンスはstatusなどいろいろ返ってきますので、必要なbodyだけ取り出します。

core.clj
(def res (http/get "http://example.com"))
(def html-data (:body @res))

enliveで欲しいデータを抜き出す

html/html-snippetでhtmlをparseして、html/selectでtitleタグの中身を取得しています。

core.clj
(def title
  (-> html-data
      (html/html-snippet)
      (html/select [:title])
      (first)
      (:content)
      (first)))

以上です。

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