Last active
May 15, 2022 11:22
-
-
Save quanon/e6894e891ffba08d8df6b07352f9706f to your computer and use it in GitHub Desktop.
MTG Mint Card の購入履歴を CSV でダウンロードする
This file contains hidden or 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
const convertTableToRows = (selector) => { | |
const table = document.querySelector(selector); | |
const rows = []; | |
const headers = Array.from(table.querySelectorAll('tr:first-child th')).map(th => th.innerText); | |
rows.push(headers); | |
table.querySelectorAll('tr').forEach(tr => { | |
const row = []; | |
tr.querySelectorAll('td').forEach(td => { | |
row.push(td.innerText); | |
if (td.colSpan && td.colSpan > 1) { | |
row.push(...new Array(td.colSpan - 1).fill('')); | |
} | |
}); | |
rows.push(row); | |
}); | |
return rows; | |
}; | |
const convertRowsToCSV = rows => { | |
return rows.map(row => row.map(value => `"${value}"`)).join("\n"); | |
}; | |
const getOrderDate = () => { | |
// Get dd element next to td element of Order Date. | |
const xpath = "//dt[text()='Order Date']/following-sibling::dd[1]"; | |
const dd = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; | |
const orderDate = new Date(dd.innerText); | |
return orderDate; | |
}; | |
const downloadCSV = (csv, filename) => { | |
const csvFile = new Blob([csv], { type: 'text/csv' }); | |
const tempLink = document.createElement('a'); | |
const orderDate = getOrderDate(); | |
tempLink.style.display = 'none'; | |
tempLink.download = filename; | |
tempLink.href = URL.createObjectURL(csvFile); | |
document.body.appendChild(tempLink); | |
tempLink.click(); | |
document.body.removeChild(tempLink); | |
return filename; | |
}; | |
const rows = convertTableToRows('table'); | |
const csv = convertRowsToCSV(rows); | |
const tempLink = document.createElement('a'); | |
const orderDate = getOrderDate(); | |
downloadCSV(csv, `${orderDate.toISOString()}.csv`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考