操纵up的人等待所有图像加载然后截图 [英] Puppeteer wait for all images to load then take screenshot

查看:75
本文介绍了操纵up的人等待所有图像加载然后截图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Puppeteer 尝试在加载所有图像之后对网站进行截图,但是可以没办法.

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.

这是到目前为止的代码,我正在使用 https://www.digg.com 作为示例网站:

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();
})();

推荐答案

有一个内置选项:

await page.goto('https://www.digg.com/', {"waitUntil" : "networkidle0"});

networkidle0 -在至少500毫秒内不超过0个网络连接时,请考虑完成导航

networkidle0 - consider navigation to be finished when there are no more than 0 network connections for at least 500 ms

networkidle2 -在至少500毫秒内不超过2个网络连接时,请考虑完成导航.

networkidle2 - consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.

P.S.当然,如果您使用的是诸如Twitter之类的无尽滚动单页应用程序,那么它将无法正常工作.

P.S. Of course it won't work if you're working with endless-scrolling-single-page-applications like Twitter.

这篇关于操纵up的人等待所有图像加载然后截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆