Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.

@emanon_was

ClojureでJsoupをラップしてみた

スクレイピング

Clojureでスクレイピングといえば既にEnliveがあるのだけれど
jQueryライクな表記はClojureのシンボルでは限界あるので
ひとまずJavaのライブラリであるところのJsoupをラップしてみた

emanon-was/cljsoup

使ってみる

1 . 準備


user> (use 'cljsoup.core)
nil

2 . URLから取ってきたHTMLをparseする


user> (def x (parse (url "https://github.com")))
#'user/x

user> x
#<Document <!DOCTYPE html> ... >

3 . Javaのクラスのままでは扱いにくいのでマッピングする


user> (nodes x)
({:type :dtd, :data ["html" "" ""]} "\n" {:tag :html, ...})

4 . CSSセレクタを使う


user> (select x "input[type=text][name=q]")
(#<Element <input type="text" data-hotkey="/ s" name="q" ...>)

user> (nodes (select x "input[type=text][name=q]"))
({:tag :input, :attrs {:type "text", :data-hotkey "/ s", :name "q", ...})

5 . 手続き的に属性(今回はname)を取ってくる


user> (-> x (select "input[type=text]") (attr "name"))
("q" "user[login]" "user[email]")

6 . HTMLを編集する(要素の直後に<div>test</div>を挿入)


user> (transform x "input[type=text]" (append (html [:div "test"])))
#<Document <!DOCTYPE html> ... >

7 . Javaのクラスから文字列に戻す

user> (parse x)
"<!DOCTYPE html> \n<html> \n <head ... "

まとめ

前回書いたdefstrictマクロを盛りまくってディスパッチしまくり
徐々にこれを拡張していってテンプレートエンジンまで持っていきたい

2
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
2
Help us understand the problem. What is going on with this article?