Created
January 8, 2012 19:04
-
-
Save takehiko/1579329 to your computer and use it in GitHub Desktop.
Book & Product Searcher with Ruby/AWS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# -*- coding: utf-8 -*- | |
# amazon-searcher.rb by takehikom | |
# run "gem install ruby-aaws" | |
# and prepare "~/.amazonrc" | |
require "rubygems" | |
require "amazon/aws/search" | |
module AmazonSearcher | |
def search(code) | |
if /^[0-9A-Z]{10}$/ =~ code | |
search_by_asin(code) | |
else | |
search_by_isbn(code) | |
end | |
end | |
def search_by_isbn(code) | |
a = Amazon::AWS::ItemSearch.new("Books", {"Keywords" => code}) | |
a.response_group = Amazon::AWS::ResponseGroup.new(:Medium) | |
req = Amazon::AWS::Search::Request.new | |
begin | |
res = req.search(a) | |
get_property(res.item_search_response.items.item) | |
rescue | |
Hash.new | |
end | |
end | |
def search_by_asin(code) | |
a = Amazon::AWS::ItemLookup.new("ASIN", {"ItemId" => code}) | |
a.response_group = Amazon::AWS::ResponseGroup.new(:Medium) | |
req = Amazon::AWS::Search::Request.new | |
begin | |
res = req.search(a) | |
get_property(res.item_lookup_response.items.item) | |
rescue | |
Hash.new | |
end | |
end | |
def get_property(item) | |
asin = item.asin.to_s | |
attr = item.item_attributes.to_h | |
attr.each_key do |key| | |
attr[key] = attr[key].to_s | |
end | |
attr["asin"] ||= asin | |
attr | |
end | |
end | |
if __FILE__ == $0 | |
include AmazonSearcher | |
h = search(ARGV.shift || "9784000295802") | |
# h = search(ARGV.shift || "B000J8KINM") | |
h.each_pair do |key, value| | |
if value.index("\n") | |
puts "#{key}:" | |
value2 = "\t" + value.chomp.gsub(/\n/, "\n\t") | |
puts value2 | |
else | |
puts "#{key}: #{value}" | |
end | |
end | |
if h.key?("asin") | |
puts | |
asin = h["asin"] | |
puts "[asin:#{asin}]" | |
puts "http://www.amazon.co.jp/dp/#{asin}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment