Repository navigation
Expand file tree
/
Copy pathscrape_408.js
More file actions
227 lines (199 loc) · 7.47 KB
/
Copy pathscrape_408.js
File metadata and controls
227 lines (199 loc) · 7.47 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
const fs = require("fs");
const path = require("path");
const https = require("https");
const http = require("http");
const cheerio = require("cheerio");
const baseUrl = "https://www.csgraduates.com";
const outputDir = "E:/code/TuringMate/408_questions";
const years = Array.from({length: 18}, (_, i) => 2009 + i);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
function fetchUrl(url) {
return new Promise((resolve, reject) => {
const client = url.startsWith("https") ? https : http;
client.get(url, { timeout: 30000 }, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
const redirectUrl = res.headers.location.startsWith("http")
? res.headers.location
: new URL(res.headers.location, url).href;
return fetchUrl(redirectUrl).then(resolve).catch(reject);
}
if (res.statusCode !== 200) {
reject(new Error(`HTTP ${res.statusCode}`));
return;
}
let data = "";
res.on("data", chunk => data += chunk);
res.on("end", () => resolve(data));
}).on("error", reject).on("timeout", function() { this.destroy(); reject(new Error("Timeout")); });
});
}
async function scrapeYear(year) {
const html = await fetchUrl(`${baseUrl}/study_methods/408quiz/${year}/`);
const $ = cheerio.load(html);
// Extract answer table
const answerMap = {};
$(".elegant-detail-content table tbody tr").each((_, row) => {
const cells = $(row).find("td");
for (let i = 0; i < cells.length; i += 2) {
const num = $(cells[i]).text().trim();
const ans = $(cells[i + 1]).text().trim();
if (num && ans) answerMap[num] = ans;
}
});
// Find all h5 elements
const h5Elements = $("h5").toArray();
const questions = [];
for (let i = 0; i < h5Elements.length; i++) {
const h5 = $(h5Elements[i]);
const qNum = h5.text().trim();
// Collect content until next h5, h4, or h3
let current = h5.next();
let questionText = "";
let options = [];
let answer = answerMap[qNum] || "";
let explanation = "";
const images = [];
const codeBlocks = [];
let isChoice = false;
// Try to find question text in <p> after h5
// First, look at the element right after h5
while (current.length > 0) {
const tagName = (current.prop("tagName") || "").toLowerCase();
if (tagName === "h5" || tagName === "h4" || tagName === "h3") break;
if (current.hasClass("choice-container")) {
isChoice = true;
// Get data-answer
const dataAns = current.attr("data-answer");
if (dataAns) answer = dataAns;
// Extract options
current.find(".choice-option").each((_, opt) => {
const label = $(opt).find(".choice-label").text().trim().replace(".", "");
const text = $(opt).find(".choice-text").text().trim();
if (label && text) options.push({ label, text });
});
// Extract explanation
const expDiv = current.find(".explanation");
if (expDiv.length > 0) {
// Get text content, cleaning HTML tags
explanation = expDiv.text().replace(/\s+/g, " ").trim();
// Also try to get the correct answer text specially
const correctAnsSpan = expDiv.find(".correct-answer-text");
if (correctAnsSpan.length > 0) {
answer = correctAnsSpan.text().trim();
}
}
// Extract SVG images from within choice container
current.find(".svg-wrapper svg").each((_, svg) => {
const svgHtml = $.html(svg);
const imgId = `img_${year}_${qNum}_${images.length + 1}`;
images.push({ id: imgId, type: "svg", content: svgHtml });
});
current.find("img").each((_, img) => {
const src = $(img).attr("src") || "";
if (src) {
const fullSrc = src.startsWith("http") ? src : baseUrl + src;
images.push({ id: `img_${year}_${qNum}_${images.length + 1}`, type: "url", content: fullSrc });
}
});
}
// Get question text from <p> elements
if (tagName === "p" && !isChoice) {
const text = current.text().trim();
if (text && !questionText) {
questionText = text;
}
}
// Extract code blocks
current.find("pre code").each((_, code) => {
codeBlocks.push($(code).text().trim());
});
current = current.next();
}
// For choice questions, look backwards for the question text <p>
if (isChoice && !questionText) {
let prev = h5.prev();
while (prev.length > 0) {
if ((prev.prop("tagName") || "").toLowerCase() === "p") {
const text = prev.text().trim();
if (text) { questionText = text; break; }
}
if ((prev.prop("tagName") || "").toLowerCase() === "h5") break;
prev = prev.prev();
}
}
// Find the subject (h4 above this h5)
let subject = "";
let prev = h5.prevAll("h4").first();
if (prev.length > 0) subject = prev.text().trim();
const qNumInt = parseInt(qNum);
if (!isNaN(qNumInt)) {
questions.push({
number: qNumInt,
type: isChoice ? "choice" : "comprehensive",
subject,
questionText,
options,
answer,
explanation,
images,
codeBlocks: codeBlocks.length > 0 ? codeBlocks : undefined
});
}
}
const choiceQuestions = questions.filter(q => q.type === "choice");
const comprehensiveQuestions = questions.filter(q => q.type === "comprehensive");
return { year, choiceQuestions, comprehensiveQuestions, answerMap };
}
async function scrapeAll() {
for (const year of years) {
process.stdout.write(`Scraping ${year}... `);
try {
const result = await scrapeYear(year);
const yearDir = path.join(outputDir, String(year));
if (!fs.existsSync(yearDir)) fs.mkdirSync(yearDir, { recursive: true });
// Save only essential data (strip large explanations for compactness)
const cleanResult = {
year: result.year,
answerMap: result.answerMap,
choiceQuestions: result.choiceQuestions.map(q => ({
number: q.number,
subject: q.subject,
questionText: q.questionText,
options: q.options,
answer: q.answer,
explanation: q.explanation,
images: q.images
})),
comprehensiveQuestions: result.comprehensiveQuestions.map(q => ({
number: q.number,
subject: q.subject,
questionText: q.questionText,
answer: q.answer,
explanation: q.explanation,
images: q.images,
codeBlocks: q.codeBlocks
}))
};
fs.writeFileSync(path.join(yearDir, "questions.json"), JSON.stringify(cleanResult, null, 2), "utf-8");
// Save SVGs
let imgCount = 0;
for (const q of [...cleanResult.choiceQuestions, ...cleanResult.comprehensiveQuestions]) {
for (const img of (q.images || [])) {
if (img.type === "svg") {
fs.writeFileSync(path.join(yearDir, `${img.id}.svg`), img.content, "utf-8");
imgCount++;
}
}
}
console.log(`OK (${cleanResult.choiceQuestions.length} choice, ${cleanResult.comprehensiveQuestions.length} comp, ${imgCount} images)`);
} catch (e) {
console.log(`ERROR: ${e.message}`);
}
await new Promise(r => setTimeout(r, 1500));
}
console.log("\n=== SCRAPING COMPLETE ===");
console.log(`Output: ${outputDir}`);
}
scrapeAll().catch(console.error);