ラベル ruby の投稿を表示しています。 すべての投稿を表示
ラベル ruby の投稿を表示しています。 すべての投稿を表示

2011年4月11日月曜日

rubyとmysqlの接続

mysqlドライバのインストール


$ gem install ruby-mysql

接続テスト


require 'rubygems'
require 'mysql'


#db = Mysql.new("localhost", "username", "password","db")
db = Mysql.connect("localhost", "username", "password","db")

⇒ エラーが出なければOK。

undefined method `connect' for Mysql:Class (NoMethodError)
もしくは `initialize': wrong number of arguments (3 for 0) (ArgumentError)
が出る場合


- 確認

1. Mysql.methods でメソッドを確認

["private_class_method", "inspect", "yaml_as", "to_yaml_style", "name", "tap", "clone", "public_methods", "object_id", "__send__", "method_defined?", "instance_variable_defined?", "equal?", "freeze", "extend", "send", "const_defined?", "methods", "ancestors", "module_eval", "instance_method", "hash", "autoload?", "dup", "to_enum", "yaml_tag_read_class", "instance_methods", "public_method_defined?", "instance_variables", "class_variable_defined?", "eql?", "constants", "id", "instance_eval", "singleton_methods", "module_exec", "to_yaml", "yaml_tag_class_name", "const_missing", "taint", "instance_variable_get", "frozen?", "enum_for", "private_method_defined?", "public_instance_methods", "display", "instance_of?", "superclass", "to_yaml_properties", "method", "to_a", "included_modules", "const_get", "instance_exec", "type", "<", "protected_methods", "<=>", "class_eval", "==", "yaml_tag_subclasses?", "class_variables", ">", "===", "instance_variable_set", "protected_instance_methods", "protected_method_defined?", "respond_to?", "kind_of?", ">=", "taguri", "public_class_method", "to_s", "<=", "const_set", "allocate", "class", "new", "private_methods", "=~", "tainted?", "__id__", "class_exec", "taguri=", "autoload", "untaint", "nil?", "private_instance_methods", "include?", "is_a?"] connect メソッドがない

2. gem list |grep mysql を確認。
mysql (2.8.1)がある。

- 対処方法

1. mysql をアンインストール

$ gem uninstall mysql

2. ruby-mysqlのインストール
⇒既にインストールしている場合はこの手順は必要ありません。

$ gem install ruby-mysql

Mac OS X環境で invalid packet: sequence number mismatch のエラーが出る場合


$gem unistall ruby-mysql
$gem install ruby-mysql -v 2.9.3
15:20 1 comment

2011年3月28日月曜日

Webクローラフレームワーク Anemone の紹介

はじめに


Anemoneはrubyで作られたWebクローラフレームワークです。実行した環境は Max OS X 10.6 です。

特徴は

  • The multi-threaded design makes Anemone fast.
  • The API makes it simple. And the expressiveness of Ruby makes it powerful

です。
意訳するとマルチスレッド対応でAPIがシンプルなとことが売りという感じでしょうか。
クライアントのプログラムがシンプルに記述出来てCLIで実行出来るので他の(言語の)プログラムとの連携が取りやすい所が気に入り試してみる事にしました。

紹介記事:クローラーを作るためのフレームワーク「Anemone」

Anemoneのインストール


$ gem install anemone

lxml,lxslt2 関連でエラーが出た場合

libxml2 is missing.
========
ERROR: Error installing nokogiri:
ERROR: Failed to build gem native extension.

/usr/local/bin/ruby extconf.rb
checking for libxml/parser.h... no
-----
libxml2 is missing. please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with installing dependencies.
-----

上記のエラーが出た場合は nokogiri のサイトを参考に します。

私のサーバのOSは Cent OSですので下記を実行しました。

$ yum install -y libxml2 libxml2-devel libxslt libxslt-devel
$ gem install anemone

問題点


最初にサンプルページにある下記のプログラムで実行しました。

require 'anemone'

Anemone.crawl("http://www.example.com/") do |anemone|
  anemone.on_every_page do |page|
      puts page.url
  end
end

Anemoneはメモリーにデータを保存するため、ページが多い時に負荷が掛かりパソコン自体の動作にも影響が出ました。
方法がないかと探すとストレージをサポートしているとの記述があります。説明は本家のサイトの下記の辺りです。

By default Anemone stores all the pages it crawls in an in-memory hash. This is fine for small sites, and is very fast. How many pages it can handle will depend on the amount of RAM in your machine, but after a certain point you will want to start storing the pages on disk during the crawl.

ストレージの選択


Anemone がサポートしているストレージは下記の通りです。

  • Redis (>= 2.0.0)
  • MongoDB
  • TokyoCabinet
  • PStore

メモリ上のデータを書き込むという目的だけなので自分の興味で MongoDB を選択しました。

mongoのインストール・起動


(1) mongoのインストール

$ wget http://fastdl.mongodb.org/osx/mongodb-osx-x86_64-1.8.0.tgz
$ tar xvfz mongodb-osx-x86_64-1.8.0.tgz
$mv mongodb-osx-x86_64-1.8.0 /usr/local/mongodb

(2) mongoの起動

バックグラウンドで起動

$ mkdir ~/tmp/mongodb
$ sudo /usr/local/mongodb/bin/mongod --dbpath ~/tmp/mongodb &

(3) Ruby ドライバのインストール

$ sudo gem install mongo
$ sudo gem install bson_ext

bson_ext は ruby 1.8.5 ではインストール出来ないようです。
CentOSのruby(1.8.5)で実行した時に下記サイトと同じ症状が発生しました。

gem install mongo_ext はruby-1.8.5 じゃダメでruby-1.8.7でおkだった

プログラム


require 'rubygems'
require 'anemone'

Anemone.crawl("http://www.example.com/") do |anemone|
  anemone.storage = Anemone::Storage.MongoDB
  anemone.on_every_page do |page|
    puts page.url
  end
end
追加したのは
anemone.storage = Anemone::Storage.MongoDB
だけ。

要望

クローラの処理で毎回全部のページを走査するのは無駄だし重いので、一回取得したサイトは一定期間処理しないとかの処理が欲しいです。折角ストレージに保存しているからあるはずと思ったのですが見当たらないようです。

crawlに指定出来るオプション


DEFAULT_OPTS = {
# run 4 Tentacle threads to fetch pages
:threads => 4,
# disable verbose output
:verbose => false,
# don't throw away the page response body after scanning it for links
:discard_page_bodies => false,
# identify self as Anemone/VERSION
:user_agent => "Anemone/#{Anemone::VERSION}",
# no delay between requests
:delay => 0,
# don't obey the robots exclusion protocol
:obey_robots_txt => false,
# by default, don't limit the depth of the crawl
:depth_limit => false,
# number of times HTTP redirects will be followed
:redirect_limit => 5,
# storage engine defaults to Hash in +process_options+ if none specified
:storage => nil,
# Hash of cookie name => value to send with HTTP requests
:cookies => nil,
# accept cookies from the server and send them back?
:accept_cookies => false,
# skip any link with a query string? e.g. http://foo.com/?u=user
:skip_query_strings => false,
# proxy server hostname
:proxy_host => nil,
# proxy server port number
:proxy_port => false,
# HTTP read timeout in seconds
:read_timeout => nil
}

を見ても無さそうです。storageはオプションで指定した方が良かったかも。。。

という事で、今回はクエリーストリングは対象には含めないのでその条件も含めて、

opts = {
:storage => Anemone::Storage.MongoDB,
:skip_query_strings => true,
}

Anemone.crawl("http://www.example.com/",opts) do |anemone|
#anemone.storage = Anemone::Storage.MongoDB
anemone.on_every_page do |page|
puts page.url
end
end

としました。
16:28 1 comment