エンジニアとしての市場価値を測りませんか?PR

企業からあなたに合ったオリジナルのスカウトを受け取って、市場価値を測りましょう

12
19

More than 3 years have passed since last update.

PA-API v5でAmazonの商品情報を取得する

Last updated at Posted at 2020-06-03

PA-APIの利用

PA-API を使ってアマゾン商品情報をとってみよう。そこからアフィリエイトなどで収益化ができたら良いね。

 PA-APIはアマゾンで一ヶ月以内に売上が発生していないと使えません。なので、アマゾンの商品リンク作成ツールや、ブログのアフィリエイトツールなどで売上を得られるように頑張ろう。ここが一番難易度が高い気がする。

 アフィリエイトで売上が発生したら次に、ISBNやASINが必要となる。ただ、ASINを具体的にどのように取るかの選択が少ないので、アマゾンのサイトをクロールしている。

Amazonの検索結果からasinをスクレイピング
https://qiita.com/99nyorituryo/items/c5d53a3ca8a4967b5927

ASINから商品情報のJSONを取得する

 ここでは、ISBNやASINという本の情報から、アマゾンの表紙画像や、タイトル著者名、出版社、価格、本の種類などの情報を取得してサイトとして出力する方法を書く。
 PAAPIでは、様々な言語用にツールが配布されているが、私はnode.jsが一番慣れているので、node.jsを用いた方法について書いていきます。

node.jsのやり方は公式のページから見てみると良いのだけど。

ここで得られたISBNをsampleGetItemsApi.jsを使ってアマゾンから書誌情報を取得する。
sampleGetItemsApi.jsは下記アドレスのnode.jsからダウンロードできる。
https://webservices.amazon.com/paapi5/documentation/quick-start/using-sdk.html

  • paapi5-nodejs-sdk-and-samplesをダウンロードして展開して
  • さっきのファイルを解凍したフォルダーで、npm install paapi5--nodejs-sdk --saveでインストール
  • アクセスキーやシークレットキーをsampleGetItemsApi.jsなどのサンプルに追加
  • またアフィリエイト用のパートナータグも追加(-22で終わるやつ)
  • sampleGetItemsApi.jsを実行してみよう

というようなことが書かれています。

アクセスキーやシークレットキーは下から取得する。
https://affiliate.amazon.co.jp/assoc_credentials/home

sampleGetItemsApi.jsを自分の目的に合うように書き換える。

初期状態では、amazon.co.jpになっていないので修正する必要がある。アクセスキーやシークレットキーを入力しないと実行できない。それから一度に取得できるasinは10個までになっている。それと待ち時間を設定しないとすぐエラーを吐くようである。

  • 100個の情報を取得しようとすると、待ち時間を設定して取得している。
  • key.jsonにアクセスキーやシークレットキー、アソシエイトタグにまとめている。
  • dateが開始日でtodateが終了日になっていてまとめて取得できる。
  • asinの配列は下の方法で作っている。

Amazonの検索結果からasinをスクレイピング
https://qiita.com/99nyorituryo/items/c5d53a3ca8a4967b5927


{"accessKey":"アクセスキー","secretKey" :"シークレットキー","PartnerTag":"パートナータグ"}

fs = require('fs');
var json = fs.readFileSync(__dirname + '/key.json', 'utf-8');
key = JSON.parse(json);

function sleep(second) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve()
        }, second * 1000)
    })
}


var ProductAdvertisingAPIv1 = require('./src/index');
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey =key.accessKey//
defaultClient.secretKey = key.secretKey//
defaultClient.host = 'webservices.amazon.co.jp';
defaultClient.region = 'us-west-2';
var api = new ProductAdvertisingAPIv1.DefaultApi();
var getItemsRequest = new ProductAdvertisingAPIv1.GetItemsRequest();
getItemsRequest['PartnerTag'] =key.PartnerTag//
getItemsRequest['PartnerType'] = 'Associates';


getItemsRequest['Resources'] =[
  "BrowseNodeInfo.BrowseNodes",
  "BrowseNodeInfo.BrowseNodes.Ancestor",
  "BrowseNodeInfo.BrowseNodes.SalesRank",
  "BrowseNodeInfo.WebsiteSalesRank",
  "Images.Primary.Small",
  "Images.Primary.Medium",
  "Images.Primary.Large",
  "ItemInfo.ByLineInfo",
  "ItemInfo.ContentRating",
  "ItemInfo.Classifications",
  "ItemInfo.ExternalIds",
  "ItemInfo.ManufactureInfo",
  "ItemInfo.ProductInfo",
  "ItemInfo.Title",
  "Offers.Listings.Price"];

var callback = function (error, data, response) {
    if (error) {
        console.log('Error calling PA-API 5.0!');
        console.log('Printing Full Error Object:\n' + JSON.stringify(error, null, 1));
        console.log('Status Code: ' + error['status']);
        if (error['response'] !== undefined && error['response']['text'] !== undefined) {
            console.log('Error Object: ' + JSON.stringify(error['response']['text'], null, 1));
        }
    } else {
    //    console.log('API called successfully.');
        var getItemsResponse = ProductAdvertisingAPIv1.GetItemsResponse.constructFromObject(data);
        console.log(JSON.stringify(getItemsResponse, null, 1));
jsondata=jsondata.concat(getItemsResponse.ItemsResult.Items);
        fs.writeFileSync(__dirname + '/json/kindle_paapi/'+filename, JSON.stringify(jsondata, null, 1),'utf-8')
//console.log("test"+jsondata)
        if (getItemsResponse['Errors'] !== undefined) {
            console.log('\nErrors:');
            console.log('Complete Error Response: ' + JSON.stringify(getItemsResponse['Errors'], null, 1));
            console.log('Printing 1st Error:');
            var error_0 = getItemsResponse['Errors'][0];
            console.log('Error Code: ' + error_0['Code']);
            console.log('Error Message: ' + error_0['Message']);
        }
    }
};

(async function(){

date=20200602
todate=20200602
for (date; date <= todate; date++) {
var json = fs.readFileSync(__dirname + '/json/kindle_asin/'+date+'k.json', 'utf-8');
asinarry = JSON.parse(json);

//c=a.ItemsResult.Items.concat(b.ItemsResult.Items);
jsondata=[];
filename=date +'.json'

for (let i = 0; i < asinarry.length; i += 10) {
 await sleep(3) 
asin =asinarry.slice(i, i+10)
getItemsRequest['ItemIds'] = asin


try {
api.getItems(getItemsRequest, callback);
} catch (ex) {
  console.log("Exception: " + ex);
}
}}
})();

これらを利用して作ったのが下のサイトである。

そしてアプリ化しました。
グーグルプレイアンドロイドアプリ

アマゾンアンドロイドアプリ

12
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Would you support @99nyorituryo?

About supporter service
99nyorituryo

Thank you for reading. I'm encouraged by your support!

Support

@99nyorituryo's pickup articles

99nyorituryo

@99nyorituryo(99)

電子書籍に関する技術書を出してます。https://www.amazon.co.jp/-/e/B07Q2TZFCN
Linked from these articles

Comments

No comments

Let's comment your feelings that are more than good

Qiita Conference 2024 Autumn will be held!: 11/14(Thu) - 11/15(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

Takahiro Anno, Masaki Fujimoto, Yukihiro Matsumoto(Matz)

View event details

Being held Article posting campaign

12
19

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address