codeなにがしの任意のユーザの記事一覧取得

2008/05/28

当サイトのトップページに自分がcodeなにがしに投稿した記事をGood Job順に表示していますが、codeなにがし運営元のOpenTypeさんがAPIを提供してくださっているおかげで簡単に記事の情報が取得できています。

そこで、エラー処理などを省いたメインの処理部分を公開します。言語はRuby-1.8.6です。

処理の流れは以下のようになっています。

1. 任意のユーザIDの記事一覧を取得(RSS)

2. 上記の記事一つ一つについて詳細情報を取得(API)

タイトルやGood Job数などの他にも更新日付や記事全文なども取得できるので目的に応じていろいろ使い道があると思います。

require "uri"
require "net/http"
require "rexml/document"
include REXML

#
# 初期設定
#
user_id = 741                             # codeなにがしユーザID

uri_all = "http://code.nanigac.com/feed/user_sources/#{user_id}?mode=rss"

#
# 記事一覧取得
#
res_all = Net::HTTP.get_response(URI.parse(uri_all))

#
# 記事毎Good Job & コメント一覧取得
#
doc_all = REXML::Document.new res_all.body

doc_all.elements.each("rdf:RDF/item") {|data|
  #
  # 記事解析
  #
  title   = data.elements['title'].text   # タイトル
  uri     = data.elements['link'].text    # 記事URI
  code_id = uri.split('/').last           # 記事ID

  #
  # 記事詳細取得
  #
  uri_item = "http://api.code.nanigac.com/getSource.php?id=#{code_id}"

  res_item = Net::HTTP.get_response(URI.parse(uri_item))

  doc_item = REXML::Document.new res_item.body

  doc_item.elements.each("source/entry") {|data|
    gj      = data.elements['gj'].text            # Good Job数
    comment = data.elements['comment_num'].text   # コメント数

    puts "#{title}(#{uri}) GJ:#{gj},comment:#{comment}"
  }
}

このプログラムを実行すると以下のような結果が得られます。

codeなにがしの任意のユーザの記事一覧取得(http://code.nanigac.com/source/view/517) GJ:1,comment:1
Perlで10進からExcelのセル番号(A,B,C...)を求める(http://code.nanigac.com/source/view/497) GJ:0,comment:0
SQLiteデータ抽出ツール(http://code.nanigac.com/source/view/493) GJ:1,comment:1
awk中でシェルの変数を使う方法(http://code.nanigac.com/source/view/420) GJ:1,comment:0
Rubyで英文メールを送信(net/smtp)(http://code.nanigac.com/source/view/404) GJ:1,comment:0
[wiki] codeなにがしについて取り上げているサイト(http://code.nanigac.com/source/wiki/view/396) GJ:5,comment:0
シェルスクリプトで当日変更ファイルを表示(http://code.nanigac.com/source/view/390) GJ:4,comment:2
Perlでホスト名 <-> IPアドレス変換(http://code.nanigac.com/source/view/381) GJ:0,comment:2
Ajaxでサーバ側のデータを強制的に取得する(http://code.nanigac.com/source/view/379) GJ:0,comment:0
JavaScriptで安全にオブジェクトの存在チェックをする(http://code.nanigac.com/source/view/374) GJ:11,comment:0
Rubyスクリプトに環境変数の値を引き渡す(http://code.nanigac.com/source/view/368) GJ:0,comment:2
RubyでRSSをパースする(http://code.nanigac.com/source/view/355) GJ:4,comment:7
Perlで外部コマンドの結果を取り込む(http://code.nanigac.com/source/view/347) GJ:1,comment:4