2

我在使用 Mechanize 提交登录表单时遇到了问题。例如,如果我需要登录到 bitbucket:

a = Mechanize.new
a.get('https://bitbucket.org/') do |page|
  login_page = a.click(page.link_with(text: 'Log In'))

  my_page = login_page.form_with(action: '/account/signin/') do |f|
    # The "username" and "password" below are the values of the "name" attribute of the two login form fields
    f.username = 'MY_ACCOUNT_NAME' 
    f.password = 'MY_PASSWORD' 
  end.click_button
end

这很简单,但是,并非所有登录表单在这两个字段上都具有相同的“名称”值。例如,WordPress 的登录表单使用 "log" 和 "pwd" 。这将使上述代码无效。

我想将一些参数传递给这个方法,以便它可以用于不同的登录表单。我试图遵循“如何从字符串转换为对象属性名称? ”但没有成功:

# auth_info is a hash
def website_login(auth_info) 
  a = Mechanize.new
  a.get(auth_info[:login_page_url]) do |page|
    land_page = page.form_with(action: auth_info[:login_form_action]) do |f|
      # Now I am stuck with these two lines
      ????????
      ????????
      # I tried to do it like this. Not working.
      f.instance_variable_set('@'+auth_info[:username_field_name], auth_info[:username])
      f.instance_variable_set('@'+auth_info[:password_field_name], auth_info[:password])
    end.click_button
  end
end

如果有人可以提供帮助,我真的很感激。

4

1 回答 1

0

解决。就像这样:

f.send(auth_info[:username_field_name] + '=', auth_info[:username])
f.send(auth_info[:password_field_name] + '=', auth_info[:password])
于 2012-10-18T08:35:18.033 回答