kasei_sanのブログ

かせいさんのIT系のおぼえがきです。胡乱の方はnoteとtwitterへ

rubyで、Amazon Product Advertising APIを使ってAmazon商品検索をしてみる

それ用のgemがある

jugend/amazon-ecs

Amazon ECS is a generic Ruby wrapper to access Amazon Product Advertising API.

APIキーを用意

Amazon Product Advertising APIで使うシークレットアクセスキーを取得する | kwLog

サンプルコード

require "rubygems"
require "amazon/ecs"
require "pry"

# 初期設定
Amazon::Ecs.configure do |options|
  options[:AWS_access_key_id] = ENV['AWS_ACCESS_KEY']        # 必須
  options[:AWS_secret_key]    = ENV['AWS_SECRET_ACCESS_KEY'] # 必須
  options[:associate_tag]     = 'kaseisantoko-22'            # 必須
  options[:search_index]      = 'Books'                      # 商品種別
  options[:response_group]    = 'Medium'                     # レスポンスに含まれる情報量(ふつう
  options[:country]           = 'jp'                         # 国
end

# 検索
res = Amazon::Ecs.item_search('ruby')

# レスポンス
p res.is_valid_request?     # =>  true  : return true if request is valid
p res.has_error?            # =>  false : return true if there is an error
p res.error                 # =>  nil   : return error message if there is any
p res.total_pages           # =>  92    : return total pages
p res.total_results         # =>  919   : return total results
p res.item_page             # =>  0     : return current page no if :item_page option is provided

# ページング
res = Amazon::Ecs.item_search('ruby', item_page: 1)
p res.item_page             # =>  1

# アイテム
item = res.items.first

# hashで欲しい

p item.get_hash

# 入れ子になっている値についてはhashにならない

# => {"ASIN"=>"4774175676",
#  "DetailPageURL"=>
#   "http://www.amazon.co.jp/Ruby%E6%8A%80%E8%A1%93%E8%80%85%E8%AA%8D%E5%AE%9A%E8%A9%A6%E9%A8%93%E5%90%88%E6%A0%BC%E6%95%99%E6%9C%AC-Silver-Gold%E5%AF%BE%E5%BF%9C-Ruby%E5%85%AC%E5%BC%8F%E8%B3%87%E6%A0%BC%E6%95%99%E7%A7%91%E6%9B%B8-%E5%A2%97%E4%BA%95-%E9%9B%84%E4%B8%80%E9%83%8E/dp/4774175676%3FSubscriptionId%3DAKIAI2M2ZUIPUQYCAK4A%26tag%3Dkaseisantoko-22%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D4774175676",
#  "ItemLinks"=>
#   "<ItemLink><Description>Add To Wishlist</Description><URL>http://www.amazon.co.jp/gp/registry/wishlist/add-item.html%3Fasin.0%3D4774175676%26SubscriptionId%3DAKIAI2M2ZUIPUQYCAK4A%26tag%3Dkaseisantoko-22%26linkCode%3Dxm2%26camp%3D2025%26creative%3D5143%26creativeASIN%3D4774175676</URL></ItemLink><ItemLink><Description>Tell A Friend</Description><URL>http://www.amazon.co.jp/gp/pdp/taf/4774175676%3FSubscriptionId%3DAKIAI2M2ZUIPUQYCAK4A%26tag%3Dkaseisantoko-22%26linkCode%3Dxm2%26camp%3D2025%26creative%3D5143%26creativeASIN%3D4774175676</URL></ItemLink><ItemLink><Description>All Customer Reviews</Description><URL>http://www.amazon.co.jp/review/product/4774175676%3FSubscriptionId%3DAKIAI2M2ZUIPUQYCAK4A%26tag%3Dkaseisantoko-22%26linkCode%3Dxm2%26camp%3D2025%26creative%3D5143%26creativeASIN%3D4774175676</URL></ItemLink><ItemLink><Description>All Offers</Description><URL>http://www.amazon.co.jp/gp/offer-listing/4774175676%3FSubscriptionId%3DAKIAI2M2ZUIPUQYCAK4A%26tag%3Dkaseisantoko-22%26linkCode%3Dxm2%26camp%3D2025%26creative%3D5143%26creativeASIN%3D4774175676</URL></ItemLink>",
#  "SalesRank"=>"23244",
#  "ImageSets"=>
#   "<ImageSet Category=\"variant\"><SwatchImage><URL>http://ecx.images-amazon.com/images/I/418qabnKqCL._SL30_.jpg</URL><Height Units=\"pixels\">30</Height><Width Units=\"pixels\">21</Width></SwatchImage><SmallImage><URL>http://ecx.images-amazon.com/images/I/418qabnKqCL._SL75_.jpg</URL><Height Units=\"pixels\">75</Height><Width Units=\"pixels\">54</Width></SmallImage><ThumbnailImage><URL>http://ecx.images-amazon.com/images/I/418qabnKqCL._SL75_.jpg</URL><Height Units=\"pixels\">75</Height><Width Units=\"pixels\">54</Width></ThumbnailImage><TinyImage><URL>http://ecx.images-amazon.com/images/I/418qabnKqCL._SL110_.jpg</URL><Height Units=\"pixels\">110</Height><Width Units=\"pixels\">79</Width></TinyImage><MediumImage><URL>http://ecx.images-amazon.com/images/I/418qabnKqCL._SL160_.jpg</URL><Height Units=\"pixels\">160</Height><Width Units=\"pixels\">114</Width></MediumImage><LargeImage><URL>http://ecx.images-amazon.com/images/I/418qabnKqCL.jpg</URL><Height Units=\"pixels\">500</Height><Width Units=\"pixels\">357</Width></LargeImage></ImageSet>",
#  "ItemAttributes"=>
#   "<Author>増井 雄一郎</Author><Author>小川 伸一郎</Author><Author>株式会社 日立ソリューションズ 牧
# 俊男</Author><Binding>単行本(ソフトカバー)</Binding><Creator Role=\"監修\">一般財団法人Rubyアソシエーション 前田 修吾</Creator><Creator Role=\"監修\">CTCテクノロジー株式会社</Creator><EAN>9784774175676</EAN><EANList><EANListElement>9784774175676</EANListElement></EANList><IsAdultProduct>0</IsAdultProduct><ISBN>4774175676</ISBN><Label>技術評論社</Label><Languages><Language><Name>日本語</Name><Type>Published</Type></Language></Languages><ListPrice><Amount>3888</Amount><CurrencyCode>JPY</CurrencyCode><FormattedPrice>¥ 3,888</FormattedPrice></ListPrice><Manufacturer>技術評論社</Manufacturer><NumberOfPages>544</NumberOfPages><PackageDimensions><Height Units=\"hundredths-inches\">102</Height><Length Units=\"hundredths-inches\">827</Length><Weight Units=\"hundredths-pounds\">115</Weight><Width Units=\"hundredths-inches\">583</Width></PackageDimensions><ProductGroup>Book</ProductGroup><ProductTypeName>ABIS_BOOK</ProductTypeName><PublicationDate>2015-08-21</PublicationDate><Publisher>技術評論社</Publisher><Studio>技術評論社</Studio><Title>Ruby技術者認定試験合格教本 Silver/Gold対応 Ruby公式資格教科書</Title>",
#  "OfferSummary"=>
#   "<LowestNewPrice><Amount>3888</Amount><CurrencyCode>JPY</CurrencyCode><FormattedPrice>¥ 3,888</FormattedPrice></LowestNewPrice><LowestUsedPrice><Amount>10105</Amount><CurrencyCode>JPY</CurrencyCode><FormattedPrice>¥ 10,105</FormattedPrice></LowestUsedPrice><TotalNew>1</TotalNew><TotalUsed>1</TotalUsed><TotalCollectible>0</TotalCollectible><TotalRefurbished>0</TotalRefurbished>"}

# 書影
item.get('ImageSets/ImageSet/MediumImage/URL')
# => "http://ecx.images-amazon.com/images/I/418qabnKqCL._SL160_.jpg"

# 詳細
p item.get_element('ItemAttributes').get_hash
# => {"Author"=>"株式会社 日立ソリューションズ 牧 俊男",
#  "Binding"=>"単行本(ソフトカバー)",
#  "Creator"=>"CTCテクノロジー株式会社",
#  "EAN"=>"9784774175676",
#  "EANList"=>"<EANListElement>9784774175676</EANListElement>",
#  "IsAdultProduct"=>"0",
#  "ISBN"=>"4774175676",
#  "Label"=>"技術評論社",
#  "Languages"=>"<Language><Name>日本語</Name><Type>Published</Type></Language>",
#  "ListPrice"=>"<Amount>3888</Amount><CurrencyCode>JPY</CurrencyCode><FormattedPrice>¥ 3,888</FormattedPrice>",
#  "Manufacturer"=>"技術評論社",
#  "NumberOfPages"=>"544",
#  "PackageDimensions"=>
#   "<Height Units=\"hundredths-inches\">102</Height><Length Units=\"hundredths-inches\">827</Length><Weight Units=\"hundredths-pounds\">115</Weight><Width Units=\"hundredths-inches\">583</Width>",
#  "ProductGroup"=>"Book",
#  "ProductTypeName"=>"ABIS_BOOK",
#  "PublicationDate"=>"2015-08-21",
#  "Publisher"=>"技術評論社",
#  "Studio"=>"技術評論社",
#  "Title"=>"Ruby技術者認定試験合格教本 Silver/Gold対応 Ruby公式資格教科書"}

Q&A

1回の検索の件数を増やせないの?

無理

電子書籍を省きたい

検索条件に含めることは無理

  • 検索結果から判別は可能
# 電子書籍かどうか?
res = Amazon::Ecs.item_search('Gene Mapper -core-')
item = res.items.first
p item.get('ItemAttributes/ProductGroup') # => eBooks

get_hash めんどい

active_support の Hash.from_xml 使えばきれいなhashにできた

xml = Amazon::Ecs.item_search('ruby').doc.to_s
result = Hash.from_xml(xml).with_indifferent_access[:ItemSearchResponse]

result[:Items][:Item].each do |item|
  pp item[:ItemAttributes][:Title]
  pp item[:ASIN]
  pp item[:DetailPageURL]
  pp item[:MediumImage][:URL]
  pp item[:ItemAttributes][:Author]
end

参考