hagino3000's blog

平成アーカイブス (更新停止)

RubyのWWW::MechanizeとHpricotでmixiの更新情報を取得する

特定のコミュニティの更新情報を取得する実験

require 'rubygems'
require 'mechanize'
require 'hpricot'

class TopicUpdInfo
	attr_accessor :title
	attr_accessor :url
	attr_accessor :updDate
	
	public
	def to_s
		puts @updDate + ' ' + @title + ' ' + @url
	end
end

# Mechanizeの設定
agent = WWW::Mechanize.new
agent.user_agent_alias = 'Mac Safari'

# ログイン処理
page = agent.get('http://mixi.jp')
search_form = page.forms.with.name('login_form').first 
search_form.email = '[メールアドレス]' 
search_form.password = '[パスワード]'
results = agent.submit(search_form)

# 対象コミュニティにアクセス
commHome = agent.get('[コミュニティのURL]')
htmlDoc = Hpricot(commHome.body)

# html解析
dates = (htmlDoc/'#newCommunityTopic div.contents dt span')
names = (htmlDoc/'#newCommunityTopic div.contents dd a')

topics = Array.new

dates.size.times { |i|
	_info = TopicUpdInfo.new
	_info.title = names[i].inner_html
	_info.url = 'http://mixi.jp/' + names[i].attributes['href']
	_info.updDate = dates[i].inner_html
	topics << _info
}

# とりあえず今は出力するだけ
topics.each { |t|
	t.to_s
}


とれたー!!
あとは対象コミュニティの登録画面やRSSフィード生成機能をつければmixi巡回が超楽になりんす。
上のコードを動かすには、[メールアドレス]と[パスワード]と[コミュニティのURL]を書き換えてください。(LL Futureでid:Yoshioriの発表を聞いておきながらPitを使わないとは何事か、という感じですがもう眠いのでごめんなさい)