0

I'm trying to use Mechanize Ruby to login to a website. I've looked at every example on this site, but an a ruby beginner and get confused as to which page I should even be getting to access the form.

Here's the code I have:

    require 'rubygems'
    require 'logger'
    require 'mechanize'

    agent = Mechanize.new
    home_page = agent.get('http://www.quora.com')
    login_form = home_page.click.form('login')

    # with email and password variables properly set
    login_form.set_fields(:session_key => 'email', :session_password=> 'password')
    return_page = agent.submit(login_form, login_form.buttons.first)

But it's returning the following error:

    forge.rb:7: undefined method `click' for #<Mechanize::Page:0x1018592b8> (NoMethodError)

How can you peak behind a page to look at whether a page contains a form?

Also, any idea how to fix the code?

  • http://stackoverflow.com/questions/17471579/trying-to-login-to-quora-using-mechanize This comment might tell you why your code is not working – Gaurav Deshmukh Nov 21 '13 at 11:44

1 Answers1

0

I believe this should work:

require 'rubygems'
require 'logger'
require 'mechanize'

agent = Mechanize.new
home_page = agent.get('http://www.quora.com')
login_form = home_page.forms.find { |form| form.fields.map(&:name).include? 'email' }

login_form.set_values :email => 'email', :password => 'password'
return_page = login_form.submit

I didn't see session_key and session_password fields on quora.com

Vlad Khomich
  • 5,820
  • 1
  • 27
  • 39
  • Hi. Thanks for answering. I replaced set_values with set_fields in the second to last line, and I got the error 500 => Net::HTTPInternalServerError (Mechanize::ResponseCodeError). That's server side, so I tried setting the useragent explicitly with agent.user_agent. Is there anything else I can try? – user1238490 Mar 02 '12 at 17:10
  • Also, how did you know that session_key and session_password fields were not present on quora.com? Where can you examine this? – user1238490 Mar 02 '12 at 17:13