読者です 読者をやめる 読者になる 読者になる

mechanizeでいい感じに

ちょっと時間ができたので、mechanizeってものを使って、mixiに日記を投稿するスクリプトを書いてみることにしました。以下がソース。

#!/opt/local/bin/ruby

require 'rubygems'
require 'mechanize'
require 'kconv'

USER = 'YOUR_MIXI_USER_ID'
PASS = 'YOUR_MIXI_PASSWORD'

if ARGV.size != 1 then
  puts "arg error"
  exit
end

diary_data = IO.readlines(ARGV[0])

if diary_data.size < 2 then
  puts "file error"
  exit
end

title = diary_data.shift.toeuc
body = diary_data[0..-1].join.toeuc

agent = WWW::Mechanize.new
page = agent.get('http://mixi.jp/')
login_form = page.forms.first
login_form['email'] = USER
login_form['password'] = PASS
login_form['next_url'] = '/home.pl'

agent.submit(login_form)

home_page = agent.get('/home.pl')
add_href = ''
home_page.links.each do |link|
  if link.href =~ /^add_diary/
    add_href = link.href
  end
end

add_page = agent.get(add_href)
add_form = add_page.forms[1]
add_form['diary_title'] = title
add_form['diary_body'] = body
confirm_page = agent.submit(add_form)

confirm_form = confirm_page.forms[1]
agent.submit(confirm_form)

これで普通に動いています。mixiのレイアウト変更があれば、すぐ使えなくなるんだけど、それまでは。