028-Crawlerは一応完成
ブログ更新滞ってしまいましたが先週の木曜日の夜中から土曜日位にかけて
- うちの子が嘔吐&下痢。でも熱も出ず元気だったので一安心
- 下痢した服の洗濯をした時が原因だと思うけど自分がウィルス性の胃腸炎にかかる
という災難にあっていました。
日曜日もですが、昨日もほぼ丸一日寝込んでいたので、回復はしたけど、この数日あまりごはんを食べてないので、ちょっと頭の働きが鈍い感じ。
Crawlerの動作を見直す
寝こむ前に、何をどこまで作っていたのか振り返っていたのですが、最初に作ったCrawlerは
- user-agent等を書いていないので、お行儀が良くない
- set_xxx のようなメソッド作っていたけど、そもそもRubyでattr_accessorがあるからそれら活用すれば無駄なメソッド減らせる
ということに気づいて、修正しました。
最終的には
require 'rubygems' require 'crawler.rb' require 'entry.rb' crawler = Crawler.new crawler.run('http://blog.pasonatech.co.jp/ooki/399/15445.html')
という感じで利用出来るようにcrawler.rbとentry.rbをそれぞれ下記のようにしました。
#crawler.rb require 'rubygems' require 'nokogiri' require 'open-uri' require 'entry.rb' class Crawler attr_accessor :html_body, :next_link, :title, :current_page def run(url) entry = Entry.new() http = open( url, "User-Agent" => "xxxxx", "From" => "h5y1m141@gmail.com", "Referer" => "http://d.hatena.ne.jp/h5y1m141" ) doc = Nokogiri::HTML(http) entry.permalink = url entry.title = doc.search('//div[@class="entry"]').search("h1").text entry.html_body = doc.search('//div[@class="entryText"]').inner_html entry.save result = doc.search('//p[@class="entrylink"]') if result.text.include?("次のエントリー»") then @next_link = result.search("a")[1]['href'] else @next_link = nil end if @next_link === nil then exit else sleep(2) self.run(@next_link) end end end
# entry.rb require 'rubygems' require 'mongoid' Mongoid.configure do |config| name = "test" host = "localhost" config.master = Mongo::Connection.new.db(name) config.slaves = [ Mongo::Connection.new(host, 27017, :slave_ok => true).db(name) ] config.persist_in_safe_mode = false end class Entry include Mongoid::Document field :permalink field :title field :html_body end
ちょっと疑問点が
http://blog.pasonatech.co.jp/の巡回する時にすぐにレスポンスがあればいいけど、そこで一定の待ち時間が発生しそう。giyo.jpの第29回 Reactorで非同期処理をやってみよう(1)を参考にして、この部分非同期処理にしたほうがよいのかなと思ったけど、実際にここは後回しにします。
次回書きたいこと
前回のエントリでも書いたけど、サイト巡回する時にどのページまで取得済なのか、どうやって管理するのか