LoginSignup
19
19

More than 5 years have passed since last update.

clj-webdriverの紹介

Last updated at Posted at 2013-12-01

◆ 以下の記事は古くなっています.記事中では v0.6.0 を使っていますが,v0.7.x 以降は Selenium-WebDriver を別途 dependencies に加えないと動きません ◆

clj-webdriver の紹介をします. clj-webdriverはSelenium-WebDriverのフロントエンドで, Clojure流のAPIを使ってブラウザを操作することが出来ます.
Rubyで言えばMechanizeと同じことが出来ると考えてよい(たぶん)ので, スクレイピングしていろいろごにょごにょするのに使えます.

$ lein new webdriver-test

project.cljにclj-webdriverを加えます.

project.clj
(defproject webdriver-test "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
-  :dependencies [[org.clojure/clojure "1.5.1"]])
+  :dependencies [[org.clojure/clojure "1.5.1"]
+                 [clj-webdriver "0.6.0"]])
$ lein deps

clj-webdriverでは, taxiというハイレベルAPIを使ってブラウジング出来ます. replの上でやるか, エディタの対話的評価機能(例: vim-fireplace)を駆使して手元で動かすとかなり試行錯誤がラクです.

(ns webdriver-test.core
  (:use [clj-webdriver.taxi]))

;; Qiitaトップページにアクセス
(set-driver! {:browser :firefox} "https://qiita.com")

これでFirefoxが起動してQiitaのトップページを開きます.

2013-12-02 at 1.28 AM.png

Twitter経由でログインさせたいので, hashmapでtagやattributesの情報を渡してfind-element(候補をすべて返す時はfind-elements)で絞り込み, clickします.

;; Twitter経由でQiitaにログイン
(click (find-element {:tag :a, :data-provider "Twitter"}))

フォーム入力はquick-fill-submitが便利です. CSSセレクタで#idhogeと書いて, その後にvalueを入れ, 最後にsubmitします.

;; TwitterにログインしてQiitaのアクセスを許可
(quick-fill-submit {"#username_or_email" "T_Hash"}
                   {"#password" "weiwei"}
                   {"#allow" submit})

これでQiitaにログインできました. 自分のストックからclojureタグの付いた投稿を検索してみます.

2013-12-02 at 1.42 AM.png

;; 自分のストックを表示してclojureタグで検索
(click (find-element {:tag :a, :href "/stock"}))
(quick-fill-submit {"*[name=q]" "tag:clojure"
                    "button[type=submit]" submit})

2013-12-02 at 2.02 AM.png

;; スクリーンショットも取れます
(take-screenshot :file "./screenshot.png")

;; 結果articleをすべて抜き出して加工するところまで書きたかったけど時間足りなくなった
;; (find-elements {:tag :article})

(quit)

スクリーンショットも取れるので(これはSelenium自体の機能ですが), 単純作業の自動化にも使えます.

19
19
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
19
19