当使用客户端函数填充 DOM 时,如何等待所有图像从 puppeteer 中的 page.evaluate 函数加载 [英] How to wait for all images to load from page.evaluate function in puppeteer when the DOM is populated using a client side function

查看:80
本文介绍了当使用客户端函数填充 DOM 时,如何等待所有图像从 puppeteer 中的 page.evaluate 函数加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让代码执行等待所有图像加载完毕,然后 puppeteer 截取屏幕截图.当调用 initData() 函数时,我的 DOM 被填充,该函数在客户端 js 文件中定义.延迟或超时是一种选择,但我相信必须有更有效的方法来做到这一点.

I am trying to make the code execution wait for all images to load before puppeteer takes a screenshot. My DOM gets populated when initData() function is called, which is defined in the client side js file. Delay or timeout is an option but I am sure there must be a more efficient way of doing it.

    (async (dataObj) => {
             const url = dataObj.url;
             const payload = dataObj.payload;
             const browser = await puppeteer.launch({ headless: false,devtools:false});
             const page = await browser.newPage();
             await page.goto(url,{'waitUntil': 'networkidle0'});

             await page.evaluate((payload) => {
               initData(payload);
                //initData is a client side function that populates the DOM, need to wait 
                //here till the images are loaded. 
               },payload)

             await page.setViewport({ width: 1280, height: 720 })
             await page.screenshot({ path: 'test.png' });
             await browser.close();
    })(dataObj)

提前致谢.

推荐答案

正如另一个答案中提到的,图像元素有complete 属性.您可以编写一个函数,当文档中的所有图像都被获取时返回 true:

As mentioned in another answer, image elements have a complete property. You can write a function that returns true when all images in the document have been fetched:

function imagesHaveLoaded() { return Array.from(document.images).every((i) => i.complete); }

你可以像这样等待那个函数:

And you can wait for that function like so:

await page.waitForFunction(imagesHaveLoaded);

将两者与您的原始代码放在一起并添加超时,使其不会无限期地等待,我们得到:

Putting the two together with your original code and adding a timeout so it doesn’t wait indefinitely, we get:

function imagesHaveLoaded() {
    return Array.from(document.images).every((i) => i.complete);
}

(async (dataObj) => {
         const url = dataObj.url;
         const payload = dataObj.payload;
         const browser = await puppeteer.launch({ headless: false, devtools: false});
         const page = await browser.newPage();
         await page.goto(url, { waitUntil: 'networkidle0' });

         await page.evaluate((payload) => {
           initData(payload);
         }, payload);

         await page.waitForFunction(imagesHaveLoaded, { timeout: YOUR_DESIRED_TIMEOUT });

         await page.setViewport({ width: 1280, height: 720 })
         await page.screenshot({ path: 'test.png' });
         await browser.close();
})(dataObj)

这篇关于当使用客户端函数填充 DOM 时,如何等待所有图像从 puppeteer 中的 page.evaluate 函数加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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