Joh*_*ohn 3 ruby forms mechanize
我正在尝试实现一个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
Run Code Online (Sandbox Code Playgroud)
终端错误消息:
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>'
Run Code Online (Sandbox Code Playgroud)
你不需要form作为参数传递给submit.这button也是可选的.尝试使用以下内容:
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
Run Code Online (Sandbox Code Playgroud)
如果您确实需要指定用于提交表单的按钮,请尝试以下操作:
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)
Run Code Online (Sandbox Code Playgroud)