Majster Majster - 6 months ago 71
Ruby Question

Google login with mechanize on ruby

I'm trying to get to google play developer console using ruby. But first I have to login. I'm trying like this:

def try_post(url, body = {}, headers = {})
unless @agent #This just creates a new mechanize instance
setup
end

puts 'Logging in'

# Hardcoded for testing purposes
@agent.get 'https://accounts.google.com/ServiceLogin?service=androiddeveloper&passive=1209600&continue=https://play.google.com/apps/publish/%23&followup=https://play.google.com/apps/publish/#identifier'

form = @agent.page.forms.find {|f| f.form_node['id'] == "gaia_loginform"}

unless form
raise 'No login form'
end

form.field_with(:id => "Email").value = @config.email

form.click_button
form = @agent.page.forms.find {|f| f.form_node['id'] == "gaia_loginform"}

unless form
raise 'No login form'
end

form.field_with(:name => "Passwd").value = @config.password

form.click_button

if @agent.page.uri.host != "play.google.com"
STDERR.puts "login failed? : uri = " + @agent.page.uri.to_s
raise 'Google login failed'
end

# @agent.post(url, body)
end


However this fails spectacularly. I tried a few other ways (trying to populate
Passwd-hidden
, finding field by
id
and so on) but no luck. I think that the password does not get entered since when I try to
puts @agent.page.body
after the final
click_button
I see enter password text somewhere in HTML.

What am I doing wrong and how can I fix it?

Answer

I've been digging around a bit more and found out that it's not that simple and I could not login with mechanize in any way.

So I ended up with using watir which was fairly simple and straightforward. Here's an example:

browser.goto LOGIN_URL

browser.text_field(:id, 'Email').set @config.email
browser.button(:id, 'next').click

browser.text_field(:id, 'Passwd').wait_until_present
browser.text_field(:id, 'Passwd').set @config.password
browser.button(:id, 'signIn').click

# Here I wait until an element on my target page is visible and then continue
browser.link(:href, '#SOMETHING').wait_until_present

Hope it helps.

Comments