Skip to content

Instantly share code, notes, and snippets.

@l-rutong
Forked from polamjag/amazon-calc.js
Last active June 4, 2021 05:53
Show Gist options
  • Save l-rutong/7479ff894fdf61186200a2bd52511ee0 to your computer and use it in GitHub Desktop.
Save l-rutong/7479ff894fdf61186200a2bd52511ee0 to your computer and use it in GitHub Desktop.
Amazon購入履歴のCSVエクスポート (2017 年バージョン)
// Amazon購入履歴のCSVエクスポート
//
// 使い方:
// 1. 全部コピーする (右上の Raw をクリックした先でやるのが楽)
// 2. Amazon の注文履歴ページ ( https://www.amazon.co.jp/gp/css/order-history/ ) を開く
// 3. F12 または 右クリ→要素の検証 とかで出てくる開発者ツールのコンソール (JavaScript REPL) にペースト
// 4. エンターで実行
// (Firefox はなんか allow pasting とタイプしろみたいなことを言われるので従う)
// 5. しばらく待つと、コンソールに合計金額が表示され、CSVが保存される
//
// 2014-12-28 / 2016-05-10 時点での DOM 構造に対応, Firefox と Chrome でテスト済
// 2017-02-18 CSV保存機能の追加
(function(){
var itemDelimiter = '\r\n';
var total = {};
var year = '2017';
var all = false;
function init(num) {
if(typeof num !== 'number') {
var num = 0;
year = window.prompt('何年分の注文を集計しますか?\n - 半角数字4桁で入力してください', year);
year = Number(year);
}
// 第二引数を true にすると各商品とかエラーを逐一表示する
var progress = load(num, false);
console.log(year + '年の集計中… / ' + (num+1) + 'ページ目');
progress.done(function(results){
if (typeof total[year] === 'undefined') {
total[year] = results;
} else {
total[year] = total[year].concat(results);
}
init(num+1);
}).fail(function(){
if(all && new Date().getFullYear() > year) {
year++;
init(0);
} else {
var _total = 0;
var _result;
jQuery.each(total, function(year, results){
var yen = 0;
jQuery.each(results, function(){
yen += this.price;
});
_total += yen;
_result = results;
});
// result
console.log('合計 ' + _total + ' 円');
download('amazon_report_'+year+'.csv',convertTocsv(_result));
}
});
}
function load(num, verbose) {
var df = jQuery.Deferred();
var page = get(num, verbose);
page.done(function(data){
var dom = jQuery.parseHTML(data);
var results = [];
jQuery(dom).find('div.order').each(function(){
var box = jQuery(this);
var dateText = jQuery(box.find('div.order-info span.value')[0]).text();
var datePattern = new RegExp("(\\d{4})年(\\d{1,2})月(\\d{1,2})日");
dateText.match(datePattern);
var year = RegExp.$1;
var month = RegExp.$2; if (month.length <= 1) month = "0" + month;
var day = RegExp.$3; if (day.length <= 1) day = "0" + day;
var date = "" + year + "年" + month + "月" + day + "日";
var orderNum = jQuery(box.find('div.order-info span.value')[2]).text().trim();
var orderDetailURL = jQuery(box.find('div.order-info a.a-link-normal')[0]).attr('href');
if(orderDetailURL!=undefined){
orderDetailURL='https://www.amazon.co.jp'+orderDetailURL;
}
else {
orderDetailURL = 'N/A';
}
var items = [];
box.find('div.a-row>a.a-link-normal').each(function(){
var itemName = jQuery(this).text().trim();
var itemPrice = jQuery(this).parent().parent().find('div.a-row>span.a-color-price').text().trim();
items.push('['+itemPrice+'] '+itemName);
});
var item = items.join(itemDelimiter);
var priceText = jQuery(box.find('div.order-info span.value')[1]).text();
var price = Number(priceText.match(/[0-9]/g).join(''));
if (verbose) console.log(item, price);
results.push({'date':date, 'orderNumber':orderNum, 'price':price, 'item':item, 'orderDetailURL':orderDetailURL});
});
if(results.length <= 0) df.reject();
else df.resolve(results);
});
return df.promise();
}
function get(num) {
var df = jQuery.Deferred();
jQuery.ajax({
url: 'https://www.amazon.co.jp/gp/css/order-history?digitalOrders=1&unifiedOrders=1&orderFilter=year-'+year+'&startIndex='+num*10,
beforeSend: function (xhr){
xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
},
})
.success(function(data){
df.resolve(data);
})
.fail(function(jqXHR, msg){
if (verbose) console.log("fail", msg);
});
return df.promise();
}
function convertTocsv(array) {
var str = '';
for (var i = 0; i < array.length; i++) {
if (str == '') {
var title = '';
for (var it in array[i]) {
if (title !== '') title += ',';
title += '"' + it + '"';
}
str += '\ufeff'+title + '\r\n';
}
var line = '';
for (var it in array[i]) {
if (line !== '') line += ',';
line += '"' + array[i][it] + '"';
}
str += line + '\r\n';
}
return str;
}
//http://stackoverflow.com/questions/2897619/using-html5-javascript-to-generate-and-save-a-file
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
if(typeof jQuery !== 'function') {
var d=document;
var s=d.createElement('script');
s.src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';
s.onload=init;
d.body.appendChild(s);
} else {
init();
}
})();
@Flinke72
Copy link

Great! Thanks a lot for your hint. 👍
I will check from time to time if new version is available which support current Amazon.jp page layout :-).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment