如何添加新的字段来机械化形式(ruby / mechanize)

一个 public class method添加领域来机械化形式

我试过了 ..

#login_form.field.new('auth_login','Login')
#login_form.field.new('auth_login','Login')

并且这两个给我一个错误未定义的方法“new”for#< WWW :: Mechanize :: Form :: Field:0x3683cbc> (NoMethodError)

我尝试login_form.field.new(‘auth_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 =登录到目前为止,它只发送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.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) }

形式的看法看起来像

[#<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">}>
]

解决方法

我想你正在寻找的是
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'

希望这可以帮助!

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...