-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
69 lines (51 loc) · 1.72 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
const puppeteer = require("puppeteer");
const SELECTOR = "#page-content > div";
const logProcess = (percent) => {
const completed = Math.min(Math.floor(percent * 40), 40);
process.stdout.write("\r\x1b[K");
process.stdout.write(
`\uD83D\uDEA7[${Array(completed).fill("=").join("")}${Array(40 - completed)
.fill("-")
.join("")}]`
);
};
const autoScroll = async (page) => {
await page.evaluate(async () => {
await new Promise((resolve) => {
const STEP = 200;
const TIME_INTERVAL = 200;
let totalHeight = 0;
const timer = setInterval(() => {
const totalDistance = document.body.scrollHeight - window.innerHeight;
window.scrollBy(0, STEP);
totalHeight += STEP;
console.log("progress", totalHeight / totalDistance);
if (totalHeight >= totalDistance) {
clearInterval(timer);
resolve();
}
}, TIME_INTERVAL);
});
});
};
(async () => {
const browser = await puppeteer.launch();
console.log("\uD83D\uDCAAStarted!");
const page = await browser.newPage();
await page.goto(process.argv[2]);
page.on("console", (consoleObj) => {
const content = consoleObj.text();
if (content.startsWith("progress")) {
logProcess(Number(consoleObj.text().split("progress ")[1]));
}
});
console.log("\u26FDStart to generate!");
await autoScroll(page);
await page.waitForSelector(SELECTOR);
const element = await page.$(SELECTOR);
await element.evaluate((el) => (el.style.padding = "16px"));
const filePath = `${await page.title()}.png`;
await element.screenshot({ path: `output/${await page.title()}.png` });
console.log(`\n\uD83C\uDF7B${filePath} generated!`);
await browser.close();
})();