2011-07-21 19 views
7

我正在嘗試使用Ruby gem Mechanize登錄亞馬遜。我總是被踢回登錄頁面,沒有任何錯誤信息。我想知道這是一個機械化錯誤還是亞馬遜阻止了這種訪問。我有下面的代碼,你可以irb來測試。無法使用Ruby Mechanize登錄亞馬遜

@mechanizer = Mechanize.new 

@mechanizer.user_agent_alias = 'Mac Safari' 

@page = @mechanizer.get("https://www.amazon.com/ap/signin?_encoding=UTF8&openid.assoc_handle=usflex&openid.return_to=https%3A%2F%2Fwww.amazon.com%2Fgp%2Fyourstore%3Fie%3DUTF8%26ref_%3Dpd_irl_gw&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.pape.max_auth_age=0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select") 

form = @page.form_with(:id => "ap_signin_form") 

field = form.field_with(:name => "email") 
field.value = "[email protected]" 

radiobutton = form.radiobutton_with(:name => 'create', :value => '0') 
radiobutton.check 

button = form.button_with(:id => "signInSubmit") 

@page = form.submit button 

感謝您的任何幫助。

回答

8

試試這個,

#!/usr/bin/env ruby 

require "rubygems" 
require "mechanize" 

class AmazonCrawler 
    def initialize 
    @agent = Mechanize.new do |agent| 
     agent.user_agent_alias = 'Mac Safari' 
     agent.follow_meta_refresh = true 
     agent.redirect_ok = true 
    end 
    end 

    def login 
    login_url = "https://www.amazon.com/ap/signin?_encoding=UTF8&openid.assoc_handle=usflex&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2Fgp%2Fyourstore%2Fhome%3Fie%3DUTF8%26ref_%3Dgno_signin" 
    @agent.get(login_url) 
    form = @agent.page.forms.first 
    form.email = "[email protected]" 
    form['ap_signin_existing_radio'] = "1" 
    form.password = "password" 
    dashboard = @agent.submit(form) 
    File.open('dashboard.html', 'w') {|file| file << dashboard.body } 
    end 
end 

AmazonCrawler.new.login 

mechanize documentation有一些很酷的例子。這cheat sheet也方便快速參考。

+0

我試圖做類似的事情,但沒有太大的成功。上面編寫的代碼仍然會將您重定向回登錄頁面。有任何想法嗎? – fffanatics

+0

我也想知道 –

+0

@fffanatics,@Zack我已更新代碼以打印出要歸檔的頁面。確保您更改「form.email」和「form.password」的值以匹配您的亞馬遜用戶憑證。它仍然爲我工作。 –