有一个公共类方法可以添加字段以机械化表单
我试过 ..
#login_form.field.new('auth_login','Login')
#login_form.field.new('auth_login','Login')
两者都给了我一个错误undefined method "new" for #<WWW::Mechanize::Form::Field:0x3683cbc> (NoMethodError)
我试过login_form.field.new('auth_login','Login')
这给了我一个错误
mechanize-0.9.3/lib/www/mechanize/page.rb:13 n `meta': undefined method `search' for nil:NilClass (NoMethodError)
但当时我提交表格。html 源中不存在该字段。我想添加它,以便我的脚本发送的 POST 查询将包含auth_username=myusername&auth_password=mypassword&auth_login=Login
到目前为止它只发送auth_username=radek&auth_password=mypassword
这可能是我无法登录的原因。只是我的想法。
脚本看起来像
require 'rubygems'
require 'mechanize'
require 'logger'
agent = WWW::Mechanize.new {|a| a.log = Logger.new("loginYOTA.log") }
agent.follow_meta_refresh = true #Mechanize does not follow meta refreshes by default, we need to set that option.
page = agent.get("http://www.somedomain.com/login?auth_successurl=http://www.somedomain.com/forum/yota?baz_r=1")
login_form = page.form_with(:method => 'POST')
puts login_form.buttons.inspect
puts page.forms.inspect
#STDIN.gets
login_form.fields.each { |f| puts "#{f.name} : #{f.value}" }
login_form['auth_username'] = 'radeks'
login_form['auth_password'] = 'TestPass01'
#login_form['auth_login'] = 'Login'
#login_form.field.new('auth_login','Login')
#login_form.field.new('auth_login','Login')
#login_form.fields.each { |f| puts "#{f.name} : #{f.value}" }
#STDIN.gets
page = agent.submit login_form
#Display welcome message if logged in
puts page.parser.xpath("/html/body/div/div/div/table/tr/td[2]/div/strong").xpath('text()').to_s.strip
puts
puts page.parser.xpath("/html/body/div/div/div/table/tr/td[2]/div").xpath('text()').to_s.strip
output = File.open("login.html", "w") {|f| f.write(page.parser.to_html) }
表单的 .inspect 看起来像
[#<WWW::Mechanize::Form
{name nil}
{method "POST"}
{action
"http://www.somedomain.com/login?auth_successurl=http://www.somedomain.com/forum/yota?baz_r=1"}
{fields
#<WWW::Mechanize::Form::Field:0x36946c0 @name="auth_username", @value="">
#<WWW::Mechanize::Form::Field:0x369451c @name="auth_password", @value="">}
{radiobuttons}
{checkboxes}
{file_uploads}
{buttons
#<WWW::Mechanize::Form::Button:0x36943b4
@name="auth_login",
@value="Login">}>
]