ruby で html から rss を生成 (その3)
xfy.com の日本語フォーラムページ https://www.xfytec.com/community/modules/newbb/index.php?cat=3
のページの RSS を生成する CGI を作ってみた。
web server で この cgi を走らせれば、RSS リーダーでフォーラム記事の新着記事をチェックできる。
xfy-forum.cgi
xfy-forum_rss.sh
xfy-forum.rb
の3ファイルから成る。
$ cat xfy-forum.cgi
#!/opt/local/bin/ruby
#----------------------------------------------------
# 2005-05-23 katoy
#
# 動作内容:
# RSS データ生成には多少時間がかかります。そこで、生成したデータは rss.xml として
# 保存しています。(rss.xml の encoding は UTF-8 です。)
#
# RSS データ取得要求がきた場合、この rss.xml が作成されたのが 30 分以内なら、
# rss.xml をそのまま返して、処理を終了します。
# そうでない場合は、投稿データをスキャンして、RSS を生成し、rss.xml として保存します。
# その後 生成した rss.xml を返して、処理を終了します。
# 参考:
# "rss で RSS 1.0 生成" http://dontstopmusic.no-ip.org/diary/20040221.html
# 記事に記載されているコードをベースにしています。
#----------------------------------------------------require 'rss/1.0'
require 'kconv'
require 'date'
require 'cgi'$NOW_TIME = Time.now # 現在の時刻
#-------------------------
def needUpdateCache(file)
if FileTest.exist?(file)
mtime = File::stat(file).mtime # 最終更新時刻
return ($NOW_TIME - mtime).divmod(60)[0] > 30 # 作成が 30 分より前なら、再作成する
return true
end
return true
end
#---------------
RSS_CACHE = "/Users/kato/Sites/xfy-forum.rss" #-- EDIT POINTprint "Content-type: text/xml; charset=UTF-8¥n¥n"
if needUpdateCache(RSS_CACHE)
system('./xfy-forum_rss.sh') #-- EDIT POINT
endFile.open(RSS_CACHE, "r"){|f| f.each {|line| print line}}
#--- End of File ---
$ cat xfy-forum_rss.sh
#!/bin/sh
/opt/local/bin/ruby xfy-forum.rb > xfy-forum.rss
$ cat xfy-forum.rb
# xfy.com のフォーラムのトップページにアクセスする。
# See http://d.hatena.ne.jp/omochist/20060919
# http://d.hatena.ne.jp/unageanu/20070504
# http://jp.rubyist.net/magazine/?0013-BundledLibrariesrequire 'rubygems'
require 'net/https'
require 'hpricot'
require 'open-uri'
require "rss"
require 'kconv'
require 'pp'site = 'www.xfytec.com'
page = '/community/modules/newbb/index.php?cat=3'
url = "https://" + site + pagehttps = Net::HTTP.new(site, 443)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE # 証明書チェックなしで接続する
https.start { |w|
response = w.get(page)
doc = Hpricot(response.body.to_s)rss = RSS::Maker.make("2.0") { |maker|
maker.channel.about = "xfy-forum.rdf"
maker.channel.title = "xfy-forum"
maker.channel.description = "xfy forum (japanese)"
maker.channel.link = urldoc.search("/html/body/table[2]/tr/td[2]/div/table[3]/tr") { |t|
# puts "------------¥n"
# puts t.search("td[2]/a/b").inner_text.to_s.tosjis
# time = Time.parse(t.search("td[5]").inner_text)
# puts time
# t.search('td[5]/a').each {|a|
# puts a.attributes['href']
# }item = maker.items.new_item
item.title = t.search("td[2]/a/b").inner_text
item.description = item.title
item.date = Time.parse(t.search("td[5]").inner_text)
t.search('td[5]/a').each {|a|
item.link = a.attributes['href']
}
}
}
puts rss.to_s.toutf8
# puts rss.to_s.tosjis
}
最近のコメント