Mechanize 2.0.1でUTF-8以外の文字化け対策
Mechanizeを使ってスクレイプしてるとUTF-8以外のページでうまくいかないことがあるので、その対策です。
http://blog.cles.jp/item/3416 からほとんどまるまるコピペなんですけど、2.0.1だと引数が変わってるみたいだったので対応しました。
Mechanizeをnewしたあとにhookを追加します
require 'rubygems' require 'mechanize' require 'nkf' agent = Mechanize.new agent.post_connect_hooks << Proc.new do |s, url, response, body| if %r|text| =~ response["Content-Type"] body.gsub!(/^.*$/mu, NKF.nkf("-wm0",body)) body.gsub(/<meta[^>]*>/) do |meta| meta.sub(/Shift_JIS|SJIS|EUC-JP/i,"UTF-8") end response["Content-Type"]="text/html; charset=utf-8" end end agent.get('http://www.rakuten.co.jp/')
gsub!のくだり何とかならないかなぁ・・・