ruby - 使用 mechanize-ruby 提交登录表单时,我可以使用变量来表示字段名称吗?

标签 ruby forms mechanize-ruby

我在使用 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/

相关文章:

ruby-on-rails - Mechanize::ResponseReadError - Content-Length 与响应正文长度不匹配

ruby-on-rails - ruby 中前导零的范围

JavaScript:无法提交表单

ruby - 多算法迷宫构建器的特定数据结构

php - 将复选框添加到 PHP POST 电子邮件表单

javascript - 如何对动态生成的表单字段实现表单验证

ruby - 如何为 Webrat、Mechanize 设置 "base URL"

ruby - 如何使用 Ruby Mechanize 设置 POST 请求的主体?

java - 允许将状态更新发布到多个站点的 API?

ruby - 在救援中捕获 Mixlib::ShellOut::ShellCommandFailed 错误