OPEN SOURCE LABORATORY

投稿日:2011年4月13日 -投稿者 S.M.

rubyでスクレイピング

今回のネタはrubyを使ったスクレイピングについてです。

PHPとかでもできますが、敢えてrubyで挑戦してみました。
ということで、早速スクレイピングしてみたいと思います。
まずは弊社HP(http://www.kdl.co.jp/)からaグのみを抜き出してみましょう。
検証した環境は以下の通り。
バージョンがちょっと古いですが、1.8系であれば最新版でも動くかと思います。
ruby 1.8.5 (2006-08-25) [i386-linux]
ruby-gem 1.3.5
nokogiri 1.4.4
ソースは以下のとおり。
■ sample.rb
$KCODE = “UTF8″
require ‘rubygems’
require ‘nokogiri’
require ‘open-uri’
page = open(“http://www.kdl.co.jp/”)
html = Nokogiri::HTML(page.read, nil, ‘UTF-8′)
html_a = html.search(‘//a’)
html_a.each_with_index do |a, i|
  puts a
end
さてさて、結果は...

Read the rest of this entry »

投稿日:2009年11月27日 -投稿者 S.M.

[Ruby] CSVとFasterCSVを比較する

前回の投稿からかなり時間が空いてしましたが、
今回は今の案件で絶賛活躍中のRubyについて書きたいと思います。

Rubyには標準でCSVを操作できるライブラリ「CSV」があります。
このCSVライブラリでもことは足りるのですが、
より高速に動く「FasterCSV」というものが公開されていたので速度比較を行ってみました。

ちなみに動作検証を行った環境とrubyのソースは以下のとおりです。

rubyのバージョン1.8.5
CSVファイルの行数:1万行 ※中身は「連番,ランダムな4文字」

◆rubyソース

require ‘csv’
require ‘rubygems’
require ‘fastercsv’
require ‘benchmark’

# 5回処理を行う。
5.times{
  Benchmark.bm do |x|
    x.report(“CSV      “) do
      array = Array.new()
      # CSVで1行ずつ取得し、配列に格納
      CSV.foreach(‘/home/homepage/list.csv’){ |row|
        array.push(“index:” + row[0] + ” | data:” + row[1])
      }
    end
 
    x.report(“FasterCSV”) do
      array = Array.new()
      # FasterCSVで1行ずつ取得し、配列に格納
      FasterCSV.foreach(‘/home/homepage/list.csv’){ |row|
        array.push(“index:” + row[0] + ” | data:” + row[1])
      }
    end
  end
}
exit

で結果は・・・

Read the rest of this entry »