WWW:mechanize

WWW.mechanaizeとは?

  • ライブラリの一つ

例えばmixiに投稿する場合

main.rb

+ ...
require 'mixidiary'

me = MixiDiary.new('hogehoge@example.co.jp', 'password')
me.login
me.edit('件名', '本文')
me.logout

mixidiary.rb

+ ...
$KCODE='EUC'
require 'mechanize'
require 'kconv'

class MixiDiary

  def initialize(username = nil, password = nil)
    @id = nil
    @username = username
    @password = password
    @agent = WWW::Mechanize.new{|a|
      begin
        a.log = Logger.new('access.log')
      rescue
        p "access.log is nothing"
      end
    }
  end

  def login
    if @username == nil || @password == nil
      p "username or password is nothing"
      exit
    end
    begin
      @agent.post('http://mixi.jp/login.pl',
                  {'email' => @username,
                   'password' => @password,
                   'next_url' => '/home.pl'}
                 )
      @page = get_page('http://mixi.jp/home.pl')
    rescue
      p "some error"
      exit
    end
  end

  def get_page(get_page_url = nil)
    @agent.get(get_page_url)
  end

  def edit(title=nil, content=nil)
    if title == nil || content == nil
      p "title or content is nothing"
      exit
    end

    if /add_diary\.pl\?id=(\d+)/ =~ @page.body
      @id = $1
    end

    edit_page = get_page('http://mixi.jp/add_diary.pl?id='+@id)

    edit_forms = edit_page.forms.name('diary').first
    edit_forms['diary_title'] = title.toeuc
    edit_forms['diary_body'] = content.toeuc
    begin
      confirm_page = @agent.submit(edit_forms)
      @agent.submit(confirm_page.forms[0]) #確認処理を常に「はい」で処理
    rescue
      p "submit error"
    end
  end

  def logout
    @agent.post('http://mixi.jp/logout.pl')
  end

end

名前:
コメント:
最終更新:2008年06月01日 16:12