使用Ruby和Mechanize填写远程登录表单之谜

3
我正在尝试实现一个Ruby脚本,该脚本将输入用户名和密码,然后填写另一个网站上的登录表单中的帐户详细信息,然后返回并跟随链接以检索帐户历史记录。为此,我使用了Mechanize宝石库。
我一直在遵循这里的示例,但似乎仍无法使其工作。为了让它逐步工作,我已经大大简化了它,但是一个看似简单的填写表单却阻碍着我。
以下是我的代码:
# 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>'

1
你确定你发布的代码会出现那个错误吗?第14行没有 form_with。看起来如果你调用了 agent.form_with,你会得到那个错误。 - ramblex
我修正了我收到的错误信息。 - John
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)

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建议不要在表单中使用块,我同意,这样会更少引起混淆。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接