やってもやらなくてもいい作業なんだけど、どちらかと言うと毎日やった方がいい作業。つい忘れがちなので自動化にチャレンジすべく、ruby + tor + privoxyを試してみる事にした。実験環境は以下の通り。
- Windows10 + Vagrant + VirturlBox
- GuestOS CentOS 6.5
- Ruby 2.3.0
torとprivoxy
そもそも今回の作業にはどちらも不要なんだけど、そのうち何かの役に立ちそうなので使ってみる事にした。まずはtorのインストールから。
[os] sudo yum install -y tor --enablerepo=epel ~~~途中省略~~~ Installed: tor.x86_64 0:0.2.9.10-1.el6 Dependency Installed: libevent2.x86_64 0:2.0.21-2.el6 torsocks.x86_64 0:2.1.0-1.el6 Complete!
サービスの起動と簡単な動作確認。なんか見たことないip addressからアクセスした事になってればとりあえず良さげ。ある程度(5分以上?)時間をおいて確認すると、全然別のアドレスになってて面白い。
[os] sudo /etc/init.d/tor start [os] curl -sL --socks5 127.0.0.1:9050 ipinfo.io { "ip": "51.15.53.134", "hostname": "No Hostname",
"city": "Haarlem", "region": "North Holland", "country": "NL",
"loc": "52.3613,4.6464", "org": "AS12876 ONLINE S.A.S.", "postal": "2034" }
続いてprivoxyのインストールと設定ファイルの変更。privoxyに来た要求はtorの動いているlocalhost:9050に流す設定をONにする。
[os] sudo yum install -y privoxy --enablerepo=epel [os] sudo vi /etc/privoxy/config ⇒以下の行を探して、コメントを外して保存 (実験環境では1336行目) forward-socks5t / 127.0.0.1:9050 .
privoxyも起動と簡単な動作確認。 結果はtorの時と同じで、privoxy→torを経由して見知らぬアドレスからのアクセスになってたらOK。↑でconfigを修正してない場合はホストOSのアドレスになってるはず。
[os] sudo /etc/init.d/privoxy start [os] curl -sL --proxy 127.0.0.1:8118 ipinfo.io { "ip": "77.247.181.163", "hostname": "lumumba.torservers.net", "city": "", "region": "", "country": "NL", "loc": "52.3824,4.8995", "org": "AS43350 NForce Entertainment B.V." }
rubyのtor-privoxy
gemを入れてみて動かしてみたが、どうやっても初期化でエラーになって使えない。
[os] gem install tor-privoxy ⇒関連するgemがズラズラインストールされる [os] irb irb> require 'tor-privoxy' => true irb> agent = TorPrivoxy::Agent.new '127.0.0.1', '', {8118 => 9050} NoMethodError: undefined method `call' for nil:NilClass Did you mean? caller from /home/vagrant/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/tor-privoxy-0.1.1/lib/tor-privoxy/agent.rb:11:in `initialize' from (irb):2:in `new' from (irb):2 from /home/vagrant/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'
git-hubのソースを見てみたら、なんか古いソースからできてる気がしたので、リポジトリのソースから自分でgem作ってみる。
[os] git clone https://github.com/pirj/tor-privoxy.git [os] cd tor-privoxy [os] gem build tor-privoxy.gemspec ⇒WARNINGがゴチャゴチャ出るが無視、gemファイルができあがる [os] gem install ./tor-privoxy-0.1.1.gem
無事動くようになったみたい。
実際のクローリング
こんな感じのコードでやりたいことはできそう。ただjavascriptが動かないのはイマイチなんだよな・・・
require 'tor-privoxy' require 'logger' agent = TorPrivoxy::Agent.new '127.0.0.1', '', {8118 => 9050} agent.log = Logger.new $stderr agent.user_agent_alias = 'iPad' page = agent.get('http://www.nikkei.com/') page.link_with(:text => /日経平均\(円\)/) do |link| link.click p "click --> #{link.href}" end
次の課題にしよう。