RubyでScrapeする時はmechanizeを使って書いているのですが、ふと毎回入れていた sleep 処理を hook で対応できないかと調べてみたところ、以下の記事を見つけました。
Regulating / rate limiting ruby mechanize - Stack Overflow
なるほど、 history_added 若干名前から想像つきにくいpropertyが存在するようです。
ソース眺めてみた
ググると他にもありそうなのでソースを眺めてみたところ、 gems/mechanize-2.7.5/lib/mechanize.rb にhook処理はまとめられていました。
content_encoding_hooks
# A list of hooks to call before reading response header 'content-encoding'. # # The hook is called with the agent making the request, the URI of the # request, the response an IO containing the response body.
content-encoding を読み込む前に呼ばれるhook処理。
content-encoding の書き換えに利用できる。
Problems with text/csv Content-Encoding = UTF-8 in Ruby Mechanize - Stack Overflow
history_added
mechanizeは内部的にhistoryの管理を行っており、historyに追加する際に呼ばれるhook。
Callback which is invoked with the page that was added to history. attr_accessor :history_added
post_connect_hooks
response取得後に呼ばれるhook処理。
# A list of hooks to call after retrieving a response. Hooks are called with # the agent, the URI, the response, and the response body.
pre_connect_hooks
response取得前に呼ばれるhook処理。
# A list of hooks to call before retrieving a response. Hooks are called # with the agent, the URI, the response, and the response body.
どれ使おうか
一見、history_added より post_connect_hooks の方が名前的にも良さそうなのですが、
redirect時の挙動が変わってきます。
1回redirectされるurlへのrequestだと、history_added は1度呼ばれますが、post_connect_hooks は2度呼ばれてしまいます。
redirect時もhookしたい場合は、post_connect_hooks、それ以外は history_added を使うのが良さそうです。