アフィリエイト リンクを使用して Amazon から注文する Mechanize でスクレーパーを作成しようとしています。目標は、ユーザーが Amazon Product API を使用してフェッチされた製品を含む私のサイトで注文できるようにし、Amazon にリダイレクトされることなく自分のサイトから注文できるようにすることです。残念ながら、Amazon には注文の部分を実行するための API がありません。そのため、スクレイパーを作成して、非常に近いですが、最終ページを通過するには助けが必要です!
私が立ち往生しているページは、クレジット カードを選択し、[続行] をクリックして注文を完了することができるページです。Amazonはある種のjavascriptを使用して、いくつかの要素を動的にロードしていると思います。ブラウザを使用してこのページにアクセスすると、追加したクレジット カードのラジオ ボタンが事前に選択されていることがわかります。チェックアウトを続行するだけです。mechanize を使用してそこに到達し、その内容をputs agent.page.body
エディターにコピーしてプレビューすると、ラジオが事前に選択されたクレジット カードを含む要素を除いて、すべてがそこにあることに気付きます。
これがコード全体です。これをコピーして Ruby コンソールに貼り付けると、最後のページに移動します。Mechanize の経験が豊富な人がこのページを読み進めるのを手伝ってくれれば、非常にありがたいです!
(これを使用するには、独自の amazon ログイン資格情報を入力する必要があります..)
agent = Mechanize.new
agent.cookie_jar.clear! #clear cookies
#Page 1 (Confirm add to cart)
page1 = agent.get("http://www.amazon.com/gp/aws/cart/add.html?ASIN.1=B0002YIQEQ&Quantity.1=1")
form = page1.forms[1]
button = form.buttons.first
page2 = agent.submit(form,button)
#Page 2 (view/update cart)
agent.page.form('cartViewForm').checkboxes.first.check
form2 = agent.page.form('cartViewForm')
form2.checkbox.check
checkoutForm = page2.form_with(:id => "gutterCartViewForm")
checkoutBtn = checkoutForm.buttons.last
page3 = agent.submit(checkoutForm, checkoutBtn)
#page3 (Sign in)
form3 = page3.form('signIn')
form3.email = 'EMAIL HERE'
form3.password = 'PASSWORD HERE'
page4 = agent.submit(form3, form3.buttons.last)
#page4 (Where do you want your items shipped?)
form4 = agent.page.form_with(:action => "/gp/buy/shipaddressselect/handlers/continue.html/ref=ox_shipaddress_add_new_addr")
form4.enterAddressFullName = 'NAME'
form4.enterAddressAddressLine1 = 'ADDRESS'
form4.enterAddressAddressLine2 = ''
form4.enterAddressCity = 'CITY'
form4.enterAddressStateOrRegion = 'ST'
form4.enterAddressPostalCode = 'ZIP'
form4.enterAddressPhoneNumber = 'PHONE'
page5 = agent.submit(form4, form4.buttons.last)
#page5 (Choose your shipping options)
agent.page.form_with(:id => "shippingOptionFormId").checkboxes.last.check
agent.page.form_with(:id => "shippingOptionFormId").submit
#page 6 (gift wrapping form)
agent.page.form_with(:id => "GiftPageContiueForm").radiobuttons_with(:class => "itemGiftWrapSelect").each do |t|
t.check
end
agent.page.form_with(:id => "GiftPageContiueForm").submit
#page7 (This is where I am stuck - continue-top is indeed the right button.
agent.page.forms.each do |t|
if t.button_with(:id => "continue-top")
form = t
button = t.button_with(:id => "continue-top")
end
end
agent.submit(form,button)