-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrapeMTGintoCSV.js
179 lines (159 loc) · 5.32 KB
/
scrapeMTGintoCSV.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
const axios = require("axios");
const { createObjectCsvWriter } = require("csv-writer");
const fs = require("fs").promises;
const LAST_PAGE_FILE = "last_page.txt";
// CSV writer setup
const csvWriter = createObjectCsvWriter({
path: "mtg_cards.csv",
header: [
{ id: "name", title: "NAME" },
{ id: "layout", title: "LAYOUT" },
{ id: "cmc", title: "CMC" },
{ id: "colors", title: "COLORS" },
{ id: "colorIdentity", title: "COLOR_IDENTITY" },
{ id: "type", title: "TYPE" },
{ id: "supertypes", title: "SUPERTYPES" },
{ id: "types", title: "TYPES" },
{ id: "subtypes", title: "SUBTYPES" },
{ id: "rarity", title: "RARITY" },
{ id: "set", title: "SET" },
{ id: "setName", title: "SET_NAME" },
{ id: "text", title: "TEXT" },
{ id: "flavor", title: "FLAVOR" },
{ id: "artist", title: "ARTIST" },
{ id: "number", title: "NUMBER" },
{ id: "power", title: "POWER" },
{ id: "toughness", title: "TOUGHNESS" },
{ id: "loyalty", title: "LOYALTY" },
{ id: "language", title: "LANGUAGE" },
{ id: "gameFormat", title: "GAME_FORMAT" },
{ id: "legality", title: "LEGALITY" },
{ id: "id", title: "ID" },
{ id: "multiverseid", title: "MULTIVERSEID" },
{ id: "names", title: "NAMES" },
{ id: "manaCost", title: "MANA_COST" },
{ id: "imageUrl", title: "IMAGE_URL" },
{ id: "watermark", title: "WATERMARK" },
{ id: "border", title: "BORDER" },
{ id: "timeshifted", title: "TIMESHIFTED" },
{ id: "hand", title: "HAND" },
{ id: "life", title: "LIFE" },
{ id: "reserved", title: "RESERVED" },
{ id: "releaseDate", title: "RELEASE_DATE" },
{ id: "starter", title: "STARTER" },
{ id: "rulings", title: "RULINGS" },
{ id: "foreignNames", title: "FOREIGN_NAMES" },
{ id: "printings", title: "PRINTINGS" },
{ id: "originalText", title: "ORIGINAL_TEXT" },
{ id: "originalType", title: "ORIGINAL_TYPE" },
{ id: "legalities", title: "LEGALITIES" },
{ id: "source", title: "SOURCE" },
],
});
const baseUrl = "https://api.magicthegathering.io/v1/cards";
// Function to handle array fields and flatten them into strings
function processCardData(card) {
// Join arrays of strings into comma-separated strings
[
"colors",
"colorIdentity",
"printings",
"supertypes",
"types",
"subtypes",
].forEach((key) => {
if (card[key]) {
card[key] = card[key].join(", ");
}
});
// Replace mana symbols with text
if (card.manaCost) {
card.manaCost = card.manaCost.replace(/{/g, "").replace(/}/g, "");
}
// Flatten nested arrays by joining their elements into a single string
["rulings", "foreignNames", "legalities"].forEach((key) => {
if (card[key]) {
card[key] = card[key]
.map((obj) => Object.values(obj).join(": "))
.join(" | ");
}
});
// Handle names array
if (card.names) {
card.names = card.names.join(", ");
}
return card;
}
async function fetchCards(page = 1, pageSize = 100) {
try {
const response = await axios.get(baseUrl, {
params: {
page,
pageSize,
},
});
// Extract headers
const totalCount = parseInt(response.headers["total-count"], 10);
const rateLimitRemaining = parseInt(
response.headers["ratelimit-remaining"],
10
);
// Log rate limit status
console.log(`Rate Limit Remaining: ${rateLimitRemaining}`);
// Check if we need to pause due to rate limiting
if (rateLimitRemaining === 0) {
// Handle rate limit reached scenario
// You could pause the execution here and resume later
console.log("Rate limit reached. Pausing execution.");
// Save the current state, for example, to a file
await writeLastPage(page);
process.exit(); // Exit the process or implement a pause mechanism
}
return {
cards: response.data.cards.map(processCardData),
totalCount,
rateLimitRemaining,
};
} catch (error) {
console.error(`Error fetching cards on page ${page}:`, error);
throw error;
}
}
async function readLastPage() {
try {
const data = await fs.readFile(LAST_PAGE_FILE, "utf8");
return parseInt(data, 10);
} catch (error) {
// If the file does not exist, start from page 1
return 1;
}
}
async function writeLastPage(page) {
await fs.writeFile(LAST_PAGE_FILE, page.toString(), "utf8");
}
async function scrapeAllCards() {
let page = await readLastPage();
let hasMoreData = true;
let totalCards;
while (hasMoreData) {
const { cards, totalCount, rateLimitRemaining } = await fetchCards(page);
totalCards = totalCount; // update totalCards with the latest totalCount from response
if (cards.length) {
await csvWriter.writeRecords(cards);
console.log(
`Page ${page} written to CSV. Total cards saved: ${page * 100}`
);
page++;
await writeLastPage(page);
} else {
hasMoreData = false;
}
// Log the progress
console.log(
`Progress: ${(((page - 1) * 100) / totalCards) * 100}% complete`
);
console.log(`Rate Limit Remaining: ${rateLimitRemaining}`);
}
console.log("Finished writing MTG card data to CSV.");
}
scrapeAllCards().catch(console.error);