amazonから取得した書籍データのXMLをファイルの保存する

ソース

require 'rubygems'
require 'amazon/ecs'

# 各出版社の書籍データをAmazonから取得し、取得したXMLデータをファイルに保存する
# ※要調査:出版社名で書籍データが取得できない出版社がある
# ※要調査:一度のリクエストで取得できる件数を増やす。
#   現状では1秒毎に10件の取得なのでamazonから取得できる書籍数を最低でも360万件(これ以上にはなるはず)として
#   計算すると少なく見積もっても360000秒(100時間)かかってしまう
class AmazonPublisherBatch
  
  def initialize(accessKeyId,associateId,country,debug)
    @booksFolderName = "amazon_books_data"  #書籍データ保存フォルダ名
    
    p "---- #{@booksFolderName}\n"
    
    @debug = debug 
    @accessKeyId = accessKeyId
    @associateId = associateId
    @country = country
    
    Amazon::Ecs.options = {
      :aWS_access_key_id => [@accessKeyId],
      :associate_tag => @associateId,
      :country => @country
    }  
    Amazon::Ecs.debug = debug
    
  end
  
  # 出版社一覧ファイルから出版社名を取得し、出版社名をキーワードにAmazonから書籍データを取得する
  def searchAll()
    # 書籍データ保存フォルダが存在しなければ作成
    if !File.exist?(@booksFolderName)
      Dir.mkdir(@booksFolderName)
    end
    
    # 出版社一覧ファイルより出版社データを取得
    publishers = getPublisherArray
    
    print "publishers.length : #{publishers.length}\n"
    
    i=0
    while i < publishers.length
      publisher_code,publisher_name = publishers[i]
      
      page = 1
      while true # 1ページ毎の処理
        print "#{Time.now} ,i : #{i} , page : #{page} ,publisher_code : #{publisher_code} , publisher_name : #{publisher_name}\n"
        
        if page == 1  # 1ページめの場合、出版社コードでフォルダを作成する。
          publisher_code_folder = File.join(@booksFolderName,publisher_code)
          if File.exist?(publisher_code_folder) then
            # フォルダが存在する場合はフォルダ内のファイルを削除
            Dir.foreach(publisher_code_folder) {|file|
              file_path = File.join(@booksFolderName,publisher_code,file)
              
              if File.ftype(File.join(@booksFolderName,publisher_code,file)) == "file" 
                #ファイルの場合は削除
                File.delete(file_path)
              end
            }
          else
            # フォルダが存在しない場合は出版社毎のフォルダを作成
            Dir.mkdir(publisher_code_folder)
          end
        end
        
        res = Amazon::Ecs.item_search('',{:item_page => page, :response_group => 'Medium', :publisher => publisher_name})
        if !res.is_valid_request? || res.has_error?  # エラーか?
          print "res.is_valid_request? : #{res.is_valid_request?}\n"
          print "res.has_error? : #{res.has_error?}\n"
          print "res.error :" #{res.error}\n"
          break
        end
        print "res.total_pages : #{res.total_pages}\n"
        print "res.total_results : #{res.total_results}\n"
        print "res.item_page : #{res.item_page}\n"
        print "res.items.size : #{res.items.size}\n"
        
        #取得したXMLをファイルに保存
        file_path = File.join(@booksFolderName,publisher_code,"#{publisher_code}_#{page}.xml")
        xml_file = File.open(file_path,"w")
        xml_file.write(res.doc)
        xml_file.close
        
        # 1秒間に1リクエストの制限があるので、取りあえず1秒待つ
        sleep(1)
        
        # この出版社の最後のページか?
        if res.item_page == res.total_pages 
          break
        end
        
        page+=1 # 次に取得するページ
      end
      
      i+=1
    end
    
  end
  
  def getPublisherArray
    array = Array.new
    
    File::open("isbn_publisher_code_test.csv") {|f1|
      f1.each {|line| 
        line.chomp!
        array.push(line.split(","))
      }
    }
    return array
  end
  
end



bat = AmazonPublisherBatch.new("ここはアクセスキーIDを設定","ここはアソシエイトIDを設定","jp",true)
bat.searchAll

上記プログラムで使用した isbn_publisher_code_test.csvの内容

282,アスキー
8222,日経BP社

実行結果

amazon_books_dataフォルダの出力内容

response_groupにMediumを指定した場合に取得出来るitemのデータ

上記プログラムではresponse_groupにMediumを指定している。
※下記のXML内はデータを削除しタグのみ表示

<item>
<asin></asin>
<detailpageurl></detailpageurl>
<smallimage>
<url></url>
<height units="pixels"></height>
<width units="pixels"></width>
</smallimage>
<mediumimage>
<url></url>
<height units="pixels"></height>
<width units="pixels"></width>
</mediumimage>
<largeimage>
<url></url>
<height units="pixels"></height>
<width units="pixels"></width>
</largeimage>
<imagesets>
<imageset category="primary">
<swatchimage>
<url></url>
<height units="pixels"></height>
<width units="pixels"></width>
</swatchimage>
<smallimage>
<url></url>
<height units="pixels"></height>
<width units="pixels"></width>
</smallimage>
<mediumimage>
<url></url>
<height units="pixels"></height>
<width units="pixels"></width>
</mediumimage>
<largeimage>
<url></url>
<height units="pixels"></height>
<width units="pixels"></width>
</largeimage>
</imageset>
</imagesets>
<itemattributes>
<author></author>
<binding></binding>
<creator role="著"></creator>
<creator role="イラスト"></creator>
<ean></ean>
<isbn></isbn>
<label></label>
<listprice>
<amount></amount>
<currencycode></currencycode>
<formattedprice></formattedprice>
</listprice>
<manufacturer></manufacturer>
<packagedimensions>
<height units="hundredths-inches"></height>
<length units="hundredths-inches"></length>
<weight units="hundredths-pounds"></weight>
<width units="hundredths-inches"></width>
</packagedimensions>
<productgroup>Book</productgroup>
<publicationdate></publicationdate>
<publisher></publisher>
<studio></studio>
<title></title>
</itemattributes>
<offersummary>
<lowestnewprice>
<amount></amount>
<currencycode></currencycode>
<formattedprice></formattedprice>
</lowestnewprice>
<lowestusedprice>
<amount></amount>
<currencycode></currencycode>
<formattedprice></formattedprice>
</lowestusedprice>
<totalnew></totalnew>
<totalused></totalused>
<totalcollectible></totalcollectible>
<totalrefurbished></totalrefurbished>
</offersummary>
</item>


Medium Response Groupで取得できるデータについては↓
http://docs.amazonwebservices.com/AWSEcommerceService/2005-09-15/
API Reference→Response Groups→ Mediumを参照

response_groupにSmallを指定した場合に取得出来るitemのデータ

※下記のXML内はデータを削除しタグのみ表示

<item>
<asin></asin>
<detailpageurl></detailpageurl>
<itemattributes>
<author></author>
<creator role="著"></creator>
<creator role="イラスト"></creator>
<manufacturer>x</manufacturer>
<productgroup></productgroup>
<title></title>
</itemattributes>
</item>
<item>


Small Response Groupで取得できるデータについては↓
http://docs.amazonwebservices.com/AWSEcommerceService/2005-09-15/
API Reference→Response Groups→ Smallを参照

response_groupにLargeを指定した場合に取得出来るitemのデータ

Large Response Groupで取得できるデータについては
http://docs.amazonwebservices.com/AWSEcommerceService/2005-09-15/
API Reference→Response Groups→ Largeを参照

Response Groupに設定可能なパラメータ

  • Accessories
  • BrowseNodeInfo
  • BrowseNodes
  • Cart
  • CartNewReleases
  • CartTopSellers
  • CartSimilarities
  • CustomerFull
  • CustomerInfo
  • CustomerLists
  • CustomerReviews
  • EditorialReview
  • Help
  • Images
  • ItemAttributes
  • ItemIds
  • Large
  • ListFull
  • ListInfo
  • ListItems
  • ListmaniaLists
  • ListMinimum
  • Medium
  • NewReleases
  • OfferFull
  • Offers
  • OfferSummary
  • Request
  • Reviews
  • SalesRank
  • SearchBins
  • Seller
  • SellerListing
  • Similarities
  • Small
  • Subjects
  • TopSellers
  • Tracks
  • TransactionDetails
  • VariationMinimum
  • Variations
  • VariationImages
  • VariationSummary