(ruby)(hpricot)(rubyでブログやニュースなどのfeedのアドレスを取得してみる)

 ブログやニュースなどのページのfeedのアドレスを取得するのには
rfeedfinderというgemがありますが、ああいうのをhpricotを使って書いたらどうなるのかを考えてみました

 今回は理解をするためですのでエラー処理や補助的な機能はあえて入れてません
簡単な説明はソースコードの方に書いてますのでそちらを参照のこと

#!ruby -Ku

# shebangは必要に応じて 「#!/usr/bin/ruby -Ku」「#!c:/ruby/bin/ruby -Ku」などに変更
# ファイルエンコードUTF-8
# ファイル名:feedfinder.rb
# ruby 1.9.3p392 (2013-02-22) [i386-mingw32]
# ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-linux]
# で動作確認

require 'rubygems'     # 環境によっては不要ですが、基本的には明記してください
require 'hpricot'      # 要インストール、例「gem install hpricot」
require 'open-uri'     # openメソッドをhttpに対応させます

con_code = 'utf-8'     # コンソールのコードを指定、Windowsならshift_jisLinuxならutf-8が一般的
http_address = ARGV[0] # コマンドライン引数1個目、feed情報が埋めこめられているページのアドレスを期待します

# コマンドライン引数で指定されたページを読み込んでhpricotでパースします
hpricot_doc = Hpricot( open(http_address).read() )

# RSSのfeedと思われる所を抽出し書き出します
# RSSのfeedと判断されるポイントは <link rel="alternate" type="application/rss+xml" ・・・ > というlinkタグが有る場合です
# 抽出されたlinkタグから各属性の値を取り出す場合は、attributes[<属性名>] とします
# 文字コードがコンソールと違っている時、出力時にコンソール上で文字化けを起こす可能性があるのでencodeで変換させてます
hpricot_doc.search('//link[@rel=\'alternate\'][@type=\'application/rss+xml\']').each{|html_tag|
        puts('' << html_tag.attributes['href'].encode(con_code) << ' (' << html_tag.attributes['title'].encode(con_code) << ')')
}
# 上と同じようにATOMのfeedと思われる所を抽出し書き出します
hpricot_doc.search('//link[@rel=\'alternate\'][@type=\'application/atom+xml\']').each{|html_tag|
        puts('' << html_tag.attributes['href'].encode(con_code) << ' (' << html_tag.attributes['title'].encode(con_code) << ')')
}

 例:
[]ruby feedfinder.rb http://d.hatena.ne.jp/morakana[]

   ↓

[]http://d.hatena.ne.jp/morakana/rss (RSS)[]
[]http://d.hatena.ne.jp/morakana/rss2 (RSS 2.0)[]
[]ruby feedfinder.rb http://www.nintendo.co.jp/news/index.html[]

   ↓

[]http://www.nintendo.co.jp/n00/whatsnew.xml (任天堂ホームページ更新情報)[]