3

ユーザー名とパスワードを受け取り、別の Web サイトのログイン フォームにアカウントの詳細を入力し、リンクをたどってアカウント履歴を取得する Ruby スクリプトを実装しようとしています。これを行うために、私は Mechanize gem を使用しています。

私はここの例に従ってきまし たが、それでもうまくいかないようです。部分的に機能させるためにこれを大幅に簡略化しましたが、フォームへの単純な入力が私を支えています。

これが私のコードです:

# script gets called with a username and password for the site
require 'mechanize'


#create a mechanize instant
agent = Mechanize.new 

agent.get('https://mysite/Login.aspx') do |login_page|

    #fill in the login form on the login page
    loggedin_page = login_page.form_with(:id => 'form1') do |form|
        username_field = form.field_with(:id => 'ContentPlaceHolder1_UserName')
        username_field.value = ARGV[0]
        password_field = form.field_with(:id => 'ContentPlaceHolder1_Password')
        password_field.value = ARGV[1]


        button = form.button_with(:id => 'ContentPlaceHolder1_btnlogin')
    end.submit(form , button)

    #click the View my history link
    #account_history_page = loggedin_page.click(home_page.link_with(:text => "View My History"))

    ####TEST to see if i am actually making it past the login page
    #### and that the View My History link is now visible amongst the other links on the page
    loggedin_page.links.each do |link|
        text = link.text.strip
        next unless text.length > 0
        puts text if text == "View My History"
    end
    ##TEST 

end

端末エラー メッセージ:

stackqv2.rb:19:in `block in <main>': undefined local variable or method `form' for main:Object (NameError)
from /usr/local/lib/ruby/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize.rb:409:in `get'
from stackqv2.rb:8:in `<main>'
4

2 に答える 2

9

formに引数として渡す必要はありませんsubmitbuttonもオプションです。以下を使用してみてください。

loggedin_page = login_page.form_with(:id => 'form1') do |form|
    username_field = form.field_with(:id => 'ContentPlaceHolder1_UserName')
    username_field.value = ARGV[0]
    password_field = form.field_with(:id => 'ContentPlaceHolder1_Password')
    password_field.value = ARGV[1]
end.submit

フォームの送信に使用するボタンを本当に指定する必要がある場合は、これを試してください。

form = login_page.form_with(:id => 'form1')
username_field = form.field_with(:id => 'ContentPlaceHolder1_UserName')
username_field.value = ARGV[0]
password_field = form.field_with(:id => 'ContentPlaceHolder1_Password')
password_field.value = ARGV[1]

button = form.button_with(:id => 'ContentPlaceHolder1_btnlogin')
loggedin_page = form.submit(button)
于 2012-12-19T16:55:05.653 に答える
2

それは範囲の問題です:

page.form do |form|
  # this block has its own scope
  form['foo'] = 'bar' # <- ok, form is defined inside this block
end

puts form # <- error, form is not defined here

ramblexの提案は、フォームでブロックを使用しないことです。私は同意します。そうすれば、混乱が少なくなります。

于 2012-12-19T20:55:04.107 に答える