使用带有Mechanize的登录表单

我知道在Stackoverflow上有相似的post,但我似乎无法弄清楚我的尝试有什么问题。

# login to the site mech.get(base_URL) do |page| l = page.form_with(:action => "/site/login/") do |f| username_field = f.field_with(:name => "LoginForm[username]") username_field.value = userName password_field = f.field_with(:name => "LoginForm[password]") password_field.value = password f.submit end end 

这是我的错误:

 rb:18:in `block (2 levels) in ': undefined method `field_with' for nil:NilClass (NoMethodError) 

这是HTML

 

Fields with * are required.

Forgot your password?

p页

 #<Mechanize::Page {url #} {meta_refresh} {title "xxxxxxxxxxx | xxxxxxxxx"} {iframes} {frames} {links # # # # # # # # # # # # # # # # # # # # #} {forms}> 

你使它变得比它需要的更复杂:

 page = mech.get base_URL form = page.form # page.forms[1], etc. form['LoginForm[username]'] = userName form['LoginForm[password]'] = password l = form.submit form.button 

为什么不直接发送post请求? 试试这个:

 respond = mech.post('www.mysite.com/site/login', "LoginForm[username]" => userName, "LoginForm[password]" => password) 

如果您知道目标(/ site / login),请求方法(post)以及必须发送的参数,请执行post请求而不会弄乱表单。

如果有效,请告诉我。

试试这个:

 mech.get(base_URL) do |page| l = page.form_with(:action => "/site/login") do |f| username_field = f.field_with(:name => "LoginForm[username]") username_field.value = userName password_field = f.field_with(:name => "LoginForm[password]") password_field.value = password end.submit end 

我删除了/在结尾处:action => "/site/login/"并在块之后直接链接submit ,如机械化示例页面中所示 。 我没有运行代码,所以让我知道它是否有效。