hpricotを使ってrailsと連携させてみた
rubyのhtmlパーサを探していて一番にHITしたhpricotというものを使ってみた。
htmlの知識さえ乏しいけど、普通に使えたので練習していこう。そして、パースした情報をrailsのDBに入れて使えるようにしてみる。
hpricotのインストール
sudo gem install hpricot
Railsとの連携用にTestプロジェクトを生成する
お手軽なsqlite3を使うように明示。
rails test -d sqlite3
cd test
あらかじめ、Topicモデルを生成しておく
ruby script/generate scaffold topic post_date:date comment:string
DBに反映
rake db:migrate
HTMLパーサのスクリプトを作成
今回は、日本ハンドボールリーグのindexページの更新情報を一覧表示するWebページを作成する。
参考サイトは以下
-out of date- ブログ版:HTMLを解析してRailsのデータベースに格納
以下を適当な名前で保存する(get_topic.rb)とする。require 'config/environment' require 'hpricot' require 'open-uri' require 'kconv' # ダウンロードしたいhtmlファイルを指定 url = 'http://www.jhl.handball.jp/index.html' file = CGI.escape(url.gsub(/http:\/\//,"")) if File.exists?(file) f = open(file) else f = open(url).read open(file, "w") {|w| w.print f } end items = Array.new doc = Hpricot(f) num = 0 # ここから重要 (doc/"li.content-list").each do |li| items[num] = {} # 掲載日を配列に格納 (li/"div.index-list-date").each do |div| items[num]['post_date'] = Time.parse(div.inner_text) end # コメントを配列に格納 (li/"div.index-list-text").each do |div| items[num]['comment'] = div.inner_text end num += 1 end # 配列をデータベースに格納 # categoryとcommentは文字コードをUTF-8に変更。 items.each do |item| topic = Topic.new topic.post_date = item['post_date'] topic.comment = item['comment'] != nil ? item['comment'].toutf8 : "" topic.save end
スクリプトを実行
ruby get_topic.rb
Webサーバ起動
ruby script/server
localhost:3000に接続