Using Ruby with Mechanize to Log in to a Site

I need to copy data from the site, but first I need my login. I use hpricot to successfully clean up other sites, but I'm new to the mechanism, and I am really puzzled by how this works.

I see that this example is usually quoted:

require 'rubygems'
require 'mechanize'

a = Mechanize.new
a.get('http://rubyforge.org/') do |page|
  # Click the login link
  login_page = a.click(page.link_with(:text => /Log In/))

  # Submit the login form
  my_page = login_page.form_with(:action => '/account/login.php') do |f|
    f.form_loginname  = ARGV[0]
    f.form_pw         = ARGV[1]
  end.click_button

  my_page.links.each do |link|
    text = link.text.strip
    next unless text.length > 0
    puts text
  end
end

But I found it extremely mysterious. In particular, I do not understand what is going on here:

f.form_loginname  = ARGV[0]
f.form_pw         = ARGV[1]

How do these page input tags suddenly become methods? Am I missing something? When I try to recreate it to go into AppDataPro (http://www.appdata.com/login), I am faced with the problem that the input name contains brackets, for example:

<Table> 
<tr><td width="150"> 
   <label for="user_session_username">Username</label><br /> 
</td><td > 
    <input id="user_session_username" name="user_session[username]" size="30" type="text" /> 
</td></tr> 
<tr><td> 
   <label for="user_session_password">Password</label><br /> 
</td><td> 
    <input id="user_session_password" name="user_session[password]" size="30" type="password" /> 
</td></tr> 
</table> 

This is my attempt to use mechanize:

    a = Mechanize.new
    a.get('http://www.appdata.com/login') do |page|
        # Click the login link
        login_page = a.click(page.link_with(:text => /Login/)) #login_page is basically a doc of appdata/login

        my_page = login_page.form_with(:action => '/login') do |f|
            f.user_session[username] =  '****username here?****'
            f.user_session[password] =  '****password here?****'
        end

    end

but causes an error

logintest01.rb:21:in `block (2 levels) in <main>': undefined method `user_session' for nil:NilClass (NoMethodError)

What happened to what I'm doing?

+5
2

, . :

username_field = form.field_with(:name => "user_session[username]")
username_field.value = "whatever_user"
password_field = form.field_with(:name => "user_session[password]")
password_field.value = "whatever_pwd"
form.submit
+13

login_page = a.click(page.link_with(:text => /Login/))

a.get('http://www.appdata.com/') do |page|
0

All Articles