それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

Mechanizeの使い方例。

RubyのMechaizeの使い方をよく忘れるので、メモする。

サンプルに図書館を使おうとして、ためにしに岡崎市立図書館を取得してみた。
岡崎市立図書館がFlashとかあり得ないサイトだった。。 まぁサンプル例として。

Mechanize起動

起動〜Basic認証設定〜ファイルを取得
require 'mechanize'
mech = Mechanize.new
#BASIC認証
mech.basic_auth("takuya", "****")
##ページ取得
mech.get("http://www.example.com");

ページ取得〜移動

mech.get("http://www.yahoo.co.jp");
##"オークション"と書かれたリンクをクリック。
mech.page.link_with( :text=>"オークション").click 
mech.page.links #リンク一覧

それでは実践してみましょう。

Google岡崎市立図書館を検索。

Googleを表示してフォームに値を入れて送信する。

mech.get("http://www.google.co.jp");
form = mech.page.forms.first
form.field_with( :name => "q").value = "岡崎市立図書館"
form.submit
mech.page.link_with( :text=>"岡崎市立図書館")
フォームのフィールドにはいろいろな手段でアクセスできる。が!!
<input type="text" ...> や <input type="password"> は取得できない

typeがRubyで使う単語だから。EVALでエラーになって、NokogiriのElementを取れない。

<input type="text" ...><input type="password"> は取得できない
実例。
#
mech.page.forms.first.fields_with :type => "text"
(eval):4: warning: Object#type is deprecated; use Object#class
(eval):4: warning: Object#type is deprecated; use Object#class
(eval):4: warning: Object#type is deprecated; use Object#class
(eval):4: warning: Object#type is deprecated; use Object#class
=> []
やりかた page.searchでXPATHで攻める。
mech.get("http://mixi.jp/")
mech.page.search('//input[@type="password"]')

ただし、NokogiriのElementになるのであとはくふうする。3月の修論を参照。ソースは後で探す。

ページのHTMLを取得する。

mech.get("http://www.google.co.jp");
form = mech.page.forms.first
form.field_with( :name => "q").value = "岡崎市立図書館"
form.submit
mech.page.link_with( :text=>"岡崎市立図書館").click
puts mech.page.body.toutf8 # mechanize#page.body で取得できる。
#他の方法
puts mech.page.parser # Nokogiri::Document::to_s で取得できる。

HTML欲しいだけならopen-uri使う方が速いけどな。

リンクをたどって蔵書検索までいく。

いきなり、リンクを飛ぶと機械っぽいので人間らしくクリックしてたどっていく。

mech.get("http://www.google.co.jp").forms.first.field_with( :name => "q").value = "岡崎市立図書館".
mech.page.forms.first.submit
mech.page.link_with( :text=>"岡崎市立図書館").click
mech.page.links.first.click
mech.page.link_with( :text=>"蔵書検索・予約").click
蔵書検索する。フォームを送信する。
mech.user_agent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; ; InfoPath.2; .NET CLR 3.5.30729;) "
mech.get("http://www.google.co.jp").forms.first.field_with( :name => "q").value = "岡崎市立図書館"
mech.page.forms.first.submit
mech.page.link_with( :text=>"岡崎市立図書館").click
mech.page.links.first.click
mech.page.link_with( :text=>"蔵書検索・予約").click
mech.page.forms.first.field_with( :name=>"key1").value="ハッカーと画家 "
mech.page.forms.first.field_with( :name=>"hidKensakuF").value = 1
mech.page.forms.first.submit

ね、簡単でしょ

たった10行で済むようなプログラムで逮捕されちゃ敵わない。
駅に設置してあるフリーペーパーを全種類持って帰っって逮捕されたようなものだ。