This repository has been archived by the owner on Jan 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (75 loc) · 2.53 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
79
80
81
82
83
84
85
"use strict";
const puppeteer = require("puppeteer");
/**
* @param {string} keyword Search query
* @param {number} limit Amount of results to query for otherwise go on indefinitely
* @param {string} userAgent User agent
* @param {object} puppeteer Puppeteer options
*/
module.exports = class EcoasiaImageScraper {
constructor({
keyword,
limit = 100,
userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/67.0.3372.0 Safari/537.36",
puppeteer = {},
}) {
if (keyword === undefined) {
throw new Error("No keyword provided");
}
this.limit = limit;
this.keyword = keyword;
this.userAgent = userAgent;
this.puppeteerOptions = puppeteer;
this.url = `https://www.ecosia.org/images?q=${keyword}`;
}
async scrape() {
try {
const browser = await puppeteer.launch({
...this.puppeteerOptions,
});
const page = await browser.newPage();
page.setUserAgent(this.userAgent);
await page.goto(this.url);
await page.setViewport({
width: 1920,
height: 1080,
});
// Target the images
await page.waitForSelector("a.image-result");
await autoScroll(page);
const images = await page.$$("a.image-result");
// Return images with unique names
const results = [];
for (let i = 0; i < this.limit; i++) {
const url = await page.evaluate(({ href }) => href, images[i]);
results.push(url);
}
if (this.limit <= results.length) {
await browser.close();
return results;
}
await browser.close();
return results;
} catch (error) {
console.log(error);
}
}
};
// Scroll the page to load additional images
const autoScroll = async page => {
await page.evaluate(async () => {
await new Promise((resolve, reject) => {
let totalHeight = 0;
const distance = 100;
const timer = setInterval(() => {
const scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if (totalHeight >= scrollHeight) {
clearInterval(timer);
resolve();
}
}, 100);
});
});
};