-
Notifications
You must be signed in to change notification settings - Fork 2
/
scraper.js
executable file
·168 lines (138 loc) · 4.43 KB
/
scraper.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
#!/usr/bin/env node
const fs = require('fs/promises');
const puppeteer = require('puppeteer');
const BASE_URL = 'https://scp-wiki.wikidot.com/'
const REGEX_MODULE_CSS = /\[\[module +css\]\]\n(.+?)\n\[\[\/module\]\]/gmis;
const REGEX_INLINE_CSS = /style="(.+?)"[^\]]*?\]\]/gi;
const REGEX_CLASSES = /class="([^\]]+?)"/gi;
const OUTPUT_FILENAME = 'output/results.json';
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function scrape(page, url, delayMs) {
try {
console.log(`* Scraping ${url}`);
await page.goto(url);
await page.waitForTimeout(delayMs);
await page.waitForSelector('#page-content');
// Check if the page doesn't exist
const pageExists = await page.evaluate(() => (
document.querySelector('#more-options-button') !== null
));
if (!pageExists) {
console.log('= Page not present, skipping');
return undefined;
}
const pageTitle = await page.evaluate(() => (
document.querySelector('#page-title').innerText.trim()
));
// Click "+ options" button
await page.waitForSelector('#more-options-button');
await page.focus('#more-options-button');
await page.click('#more-options-button');
// Click "page source" button
await page.waitForSelector('#view-source-button');
await page.focus('#view-source-button');
await page.click('#view-source-button');
// Copy page source
await page.waitForSelector('.page-source');
await page.focus('.page-source');
const pageSource = await page.evaluate(() => {
const pageSourceElement = document.querySelector('.page-source');
if (pageSourceElement === null) {
throw "Can't find page source element";
}
return pageSourceElement.innerHTML
.replace(/<br>/g, '') // Newlines are already present in the source
.replace(/ /g, ' ')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/^\n\t/, ''); // It starts with a newline and a tab for some reason
});
// Extract CSS
const moduleStyles = [];
for (const match of pageSource.matchAll(REGEX_MODULE_CSS)) {
moduleStyles.push(match[1]);
}
const inlineStyles = [];
for (const match of pageSource.matchAll(REGEX_INLINE_CSS)) {
inlineStyles.push(match[1]);
}
const classes = [];
for (const match of pageSource.matchAll(REGEX_CLASSES)) {
const klasses = match[1].split(' ');
for (const klass of klasses) {
classes.push(klass);
}
}
return { pageSource, pageTitle, moduleStyles, inlineStyles, classes };
} catch (error) {
console.error(error);
throw error;
}
}
async function readStyles() {
try {
const stylesJSON = await fs.readFile(OUTPUT_FILENAME);
const styles = JSON.parse(stylesJSON);
console.log(`Loaded ${Object.keys(styles).length} styles...`);
return styles;
} catch (error) {
console.log('Cannot load pre-existing styles.');
return {};
}
}
async function main() {
const extractedStyles = await readStyles();
let browser;
async function saveStyles() {
const json = JSON.stringify(extractedStyles, null, 4);
await fs.writeFile(OUTPUT_FILENAME, json);
}
function scpSlug(number) {
if (number < 1000) {
return 'scp-' + String(number).padStart(3, '0');
} else {
return 'scp-' + String(number).padStart(4, '0');
}
}
async function extract(page, slug) {
const DELAYS_MS = [500, 2000, 6000];
const url = BASE_URL + slug;
// Scraping attempts
for (let i = 0; i < 3; i++) {
try {
extractedStyles[slug] = await scrape(page, url, DELAYS_MS[i]);
break;
} catch (error) {
if (i < 2) {
console.log('! Failed to scrape, retrying...')
} else {
console.log('! Failed to scrape, giving up!')
}
}
}
// Save every iteration to allow continuation
await saveStyles();
// Avoid rate-limiting
await sleep(2000);
}
try {
console.log("Starting up scraper...");
browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
for (let i = 0; i < 7000; i++) {
const slug = scpSlug(i);
if (extractedStyles[slug] === undefined) {
await extract(page, slug);
}
}
} catch (error) {
console.error(`Error running scraper: ${error}`);
} finally {
await browser.close();
await saveStyles();
}
}
main();