-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
78 lines (68 loc) · 2.08 KB
/
index.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
const path = require('path');
const puppeteer = require('puppeteer');
const download = require('image-downloader');
// Relative path to directory to download images
const IMAGE_DIRECTORY = './images';
const puppeteerOptions = {};
if (process.env.USING_DOCKERFILE) {
console.log('--- Running inside docker ---');
puppeteerOptions.args = ['--disable-dev-shm-usage'],
puppeteerOptions.executablePath = '/usr/bin/chromium-browser'
}
const scrapeImgUrls = async () => {
try {
console.log('🚀 Launching...');
// Launches puppeteer and goes to URL
const browser = await puppeteer.launch(puppeteerOptions);
const page = await browser.newPage();
console.log('🌎 Visiting web page...');
await page.goto('https://old.reddit.com/r/fakealbumcovers/');
console.log('⛏ Scraping image URLs...');
const results = await page.evaluate(() => {
// Grabs all <divs> of images
const elements = document
.querySelectorAll('.content > .spacer > #siteTable > .thing');
/*
* Spreads elements into an array to filter, then creates a new array of
* only the URLs
* You can customize this to add another filter below the first if
* looking for more specific criteria -- refer to blog post
*/
return [...elements]
.filter(el => el.dataset.url.search(/(.jpg)|(.png)/) >= 0)
.map(el => el.dataset.url)
});
browser.close();
return results;
}
catch(e) {
console.log(e);
throw e;
}
}
const downloadImg = async (options = {}) => {
try {
const { filename, image } = await download.image(options);
console.log('⬇️ ', path.basename(filename)); // => image.jpg
}
catch (e) {
throw e;
}
}
const downloadAll = async () => {
const imgs = await scrapeImgUrls();
try {
await Promise.all(imgs.map(async (file) => {
await downloadImg({
url: file,
dest: IMAGE_DIRECTORY
});
}));
console.log(`👌 Done -- downloaded \x1b[36m${imgs.length}\x1b[0m album covers!`);
}
catch(e) {
console.log(e);
throw e;
}
}
downloadAll();