我在使用机械化提交登录表单时遇到了一个问题。例如,如果我需要登录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"one_answers" 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
真的很感激是否有人可以提供帮助。
解决。就是这样:
f.send(auth_info[:username_field_name] + '=', auth_info[:username])
f.send(auth_info[:password_field_name] + '=', auth_info[:password])