我在使用 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”。这将使上述代码无效。
我想将一些参数传递给这个方法,以便它可以用于不同的登录表单。 我试图关注“How to convert from a string to object attribute name?”但没有成功:
# 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])
关于ruby - 使用 mechanize-ruby 提交登录表单时,我可以使用变量来表示字段名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12938998/