Ruby で Amazon Product Advertising API を使ったメモ
はじめに
- Ruby で amazon-ecs を使って Amazon Product Advertising API の検索をしたメモ。
インストール
gem 'amazon-ecs'
アカウント作成
Amazon アソシエイトのID作成
商品リストの検索
初期化
require 'amazon/ecs' Amazon::Ecs.options = { :associate_tag => 'Amazon アソシエイトのID', :AWS_access_key_id => 'AWS のアクセスキー', :AWS_secret_key => 'AWS のシークレットキー' }
キーワードで検索
# 検索の実行 / オプションの詳細は後述 amazon = Amazon::Ecs.item_search( 'キーワード', :search_index => 'Books', #=> 検索対象の指定 / 詳細は後述 :response_group=>"Large", #=> レスポンスに含まれる要素の指定 / 詳細は後述 :country => 'jp' ) # 各商品ごとに処理 amazon.items.each do |item| puts item.class #=> 商品ごとに Amazon::Element のインスタンスが渡される puts item.get('ItemAttributes/Title') #=> タイトルの取得(Amazon::Element.get(PATH) でパスを指定して値の取得) puts item.get('DetailPageURL') #=> 商品詳細URL puts item.get("LargeImage/URL") #=> 商品画像URL puts item.get_element('ItemAttributes').get("Title") #=> Amazon::Element.get_element(ELEMENT_NAME) で子要素を取得 puts item.get_element('ItemAttributes').elem.css("Title").text #=> Amazon::Element.elem で Nokogiri::XML::Element が取得できるので、css や xpath で要素の検索ができる end
検索オプション
- https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html を参考に
- パラメータ名を snake_case にする
search_index
- 検索対象の指定
- All で全て、Books で本、KindleStore でKindle本、その他は https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html を参照。
response_group
- レスポンスに含まれる要素の指定
- キーワードで指定し、復数の場合はカンマ区切りにする
- search_index によって指定可能な値が異なる
- 指定可能な値は https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html を参照
- Small, Medium, Large はそれぞれのサイズ感でよく使うものをまとめてある
browse_node
- 検索カテゴリーの指定。カテゴリーのIDを整数で指定する。
- IDの表などは見つけられなかったが、www.amazon.co.jp のカテゴリー別商品ページなどの URL から推測できる。
- 商品ページのURL が http://www.amazon.co.jp/%E6%9C%AC-%E9%80%9A%E8%B2%A9/b/ref=nav_jb?ie=UTF8&node=465392 の場合は 465392
item_page
- 商品は1リクエストで10件取得され、11件目以降は item_page でページ数を指定して取得する。
- 指定できる値は1〜10
実行例
Kindleストアでコミックを検索し売り上げ順にソートした2ページ目を取得、カテゴリーのIDを表示する。
amazon = Amazon::Ecs.item_search( '', #=> browse_node 指定時にはキーワードは省略可 :search_index => 'KindleStore', :response_group=>"Small, BrowseNodes", :country => 'jp', :browse_node => '2293143051', :sort => "salesrank", :item_page => "2" ) amazon.items.each do |item| puts "Title: " + item.get('ItemAttributes/Title') puts item.get("BrowseNodes/BrowseNode/BrowseNodeId") #=> メインのカテゴリーID if item.get_element("BrowseNodes/BrowseNode/Children") then #=> サブのIDがあれば表示 item.get_element("BrowseNodes/BrowseNode/Children").elem.children.each {|c| puts c.css("BrowseNodeId").text } end end