如何为机械化forms添加新字段(ruby / mechanize)
有一个公共类方法可以向机械化表单添加字段
我试过了 ..
#login_form.field.new('auth_login','Login') #login_form.field.new('auth_login','Login')
并且两个都给了我一个错误undefined method "new" for # (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 # #} {radiobuttons} {checkboxes} {file_uploads} {buttons #}> ]
我想你要找的是
login_form.add_field!(field_name, value = nil)
以下是文档:
http://rdoc.info/projects/tenderlove/mechanize
除了向表单添加字段的方法不多之外,它与方法WWW :: Mechanize :: Form :: Field.new之间的区别并不大。 这是add_field的方法! 方法实现….你可以看到它正是你所期望的。 它实例化一个Field对象,然后将其添加到表单的’fields’数组中。 您将无法在代码中执行此操作,因为方法“fields <<”是“Form”中的私有方法。
# File lib/www/mechanize/form.rb, line 65 def add_field!(field_name, value = nil) fields << Field.new(field_name, value) end
在旁注中,根据文档,您应该能够做出您提出的第一个变体:
login_form['field_name']='value'
希望这可以帮助!
另一种如何添加新字段的方法是在发布表单时这样做
page = agent.post( url, {'auth_username'=>'myusername', #existing field 'auth_password'=>'mypassword', #existing field 'auth_login'=>'Login'}) #new field