Puppeteer 等待所有图像加载然后截屏 [英] Puppeteer wait for all images to load then take screenshot
问题描述
我正在使用 Puppeteer 尝试在所有图片加载后截取网站的屏幕截图,但可以不让它工作.
这是我目前得到的代码,我使用的是 https://www.digg.com 作为示例网站:
const puppeteer = require('puppeteer');(异步() => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://www.digg.com/');等待 page.setViewport({width: 1640, height: 800});等待 page.evaluate(() => {返回 Promise.resolve(window.scrollTo(0,document.body.scrollHeight));});等待 page.waitFor(1000);等待 page.evaluate(() => {var images = document.querySelectorAll('img');函数预加载(){var 承诺 = [];函数加载图像(img){返回新的承诺(功能(解决,拒绝){如果(img.complete){解决(img)}img.onload = 函数(){解决(img);};img.onerror = 函数(e){解决(img);};})}for (var i = 0; i
有一个 内置选项:
await page.goto('https://www.digg.com/', {"waitUntil" : "networkidle0"});
<块引用>
networkidle0 - 当至少 500 ms 的网络连接不超过 0 个时,认为导航完成
networkidle2 - 当至少 500 毫秒的网络连接不超过 2 个时,认为导航已完成.
附言当然,如果您使用的是像 Twitter 这样无限滚动的单页应用程序,它就行不通了.
I am using Puppeteer to try to take a screenshot of a website after all images have loaded but can't get it to work.
Here is the code I've got so far, I am using https://www.digg.com as the example website:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.digg.com/');
await page.setViewport({width: 1640, height: 800});
await page.evaluate(() => {
return Promise.resolve(window.scrollTo(0,document.body.scrollHeight));
});
await page.waitFor(1000);
await page.evaluate(() => {
var images = document.querySelectorAll('img');
function preLoad() {
var promises = [];
function loadImage(img) {
return new Promise(function(resolve,reject) {
if (img.complete) {
resolve(img)
}
img.onload = function() {
resolve(img);
};
img.onerror = function(e) {
resolve(img);
};
})
}
for (var i = 0; i < images.length; i++)
{
promises.push(loadImage(images[i]));
}
return Promise.all(promises);
}
return preLoad();
});
await page.screenshot({path: 'digg.png', fullPage: true});
browser.close();
})();
There is a built-in option for that:
await page.goto('https://www.digg.com/', {"waitUntil" : "networkidle0"});
networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms
networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.
P.S. Of course it won't work if you're working with endless-scrolling-single-page-applications like Twitter.
这篇关于Puppeteer 等待所有图像加载然后截屏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!