puppeteer 如何等待页面加载完再截图?

如题,因为要截取的页面是有向后台发起数据请求的,每次截图都是请求前的图,一片空白,如何才能截取数据加载完成后的网页图?

尝试过网上:page.waitForNavigation,报错:Navigation Timeout Exceeded

报错信息:

node screenshot.js
(node:12992) UnhandledPromiseRejectionWarning: TimeoutError: Navigation Timeout Exceeded: 10000ms exceeded
    at Promise.then (f:\demo\autoDevtool\node_modules\puppeteer\lib\LifecycleWatcher.js:142:21)
  -- ASYNC --
    at Frame.<anonymous> (f:\demo\autoDevtool\node_modules\puppeteer\lib\helper.js:111:15)
    at Page.waitForNavigation (f:\demo\autoDevtool\node_modules\puppeteer\lib\Page.js:694:49)
    at Page.<anonymous> (f:\demo\autoDevtool\node_modules\puppeteer\lib\helper.js:112:23)
    at puppeteer.launch.then (f:\demo\autoDevtool\2019-9-17\screenshot.js:24:20)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12992) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12992) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

代码:

// 截图
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');

(async () => {
   const browser = await puppeteer.launch({
        // args: ['--no-sandbox'],
        // args: ['--no-sandbox', '--disable-setuid-sandbox'],
        //  ignoreDefaultArgs: ['--disable-extensions'],
        executablePath: "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
        headless: false,
        defaultViewport: {
            width: 1920,
            height: 937
        },
        // timeout: 3000

    }).then(async browser => {
        const page = await browser.newPage()

        await page.goto('https://www.jianshu.com/p/56babda610f9')
        await page.waitForNavigation({
            waitUntil: "load",
            timeout: 10000
        })
        await page.screenshot({
            path: './jianshu.png'

        })

        await browser.close()
    })


})()
阅读 28.6k
3 个回答
  const browser = await puppeteer.launch();

  const page = await browser.newPage();
  
  await page.goto('https://www.baidu.com');

  await page.content();

  await page.screenshot({ path: './1.png' });

  // 用完记得关闭

  await page.close();
    
  await browser.close();

goto 有个 options 就下面这个,你去看看:
waitUntil: networkidle0

const page = await browser.newPage()
await page.goto(url, {
    waitUntil: 'networkidle0'
})

waitUntil参数是来确定满足什么条件才认为页面跳转完成。包括以下事件:

  • load - 页面的load事件触发时
  • domcontentloaded - 页面的DOMContentLoaded事件触发时
  • networkidle0 - 不再有网络连接时触发(至少500毫秒后)
  • networkidle2 - 只有2个网络连接时触发(至少500毫秒后)

可以参考https://mp.weixin.qq.com/s/P-YdQPOQ9GZgjDEP7VG8ag

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏