【问题标题】:Cannot take a screenshot using puppeteer, it dumps an empty image file无法使用 puppeteer 截取屏幕截图,它会转储一个空图像文件
【发布时间】:2017-12-29 18:32:23
【问题描述】:

我有一个名为 test.html 的骨架 html 文件,它包含以下内容:

<!doctype html>
<html>

<head>
</head>

<body>
</body>

</html>

然后我有另一个文件,旨在用chrome headless打开上述文件,在其中添加图像然后截图,看看:

const puppeteer = require('puppeteer')
const fs = require('fs');

(async() => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('file://test.html')
  await page.$eval('body', (body) => {
    const imgElement = new window.Image()
    imgElement.src = 'https://user-images.githubusercontent.com/10379601/29446482-04f7036a-841f-11e7-9872-91d1fc2ea683.png'
    body.appendChild(imgElement)
  })
  await page.waitForSelector('img')
  fs.writeFileSync('output.html', await page.content())
  await page.screenshot({
    path: 'screenshot.jpg'
  })
  await browser.close()
})()

运行此代码后,我得到一个空图像文件作为屏幕截图。您还可以注意到,我正在使用以下方式转储页面内容:

fs.writeFileSync('output.html', await page.content())

在我的浏览器中打开output.html 包含我在屏幕截图中所期望的图像。那为什么生成的截图是空的呢?

【问题讨论】:

    标签: javascript node.js puppeteer google-chrome-headless


    【解决方案1】:

    这是因为您没有等待图像下载。您只在等待await page.waitForSelector('img'),但这个等待的是 DOM 元素,而不是实际的图像。这是图像下载和截屏之间的竞争条件。 你应该像这样等待图像onload

    await page.$eval('body', async (body) => {
        const imgElement = new window.Image()
        imgElement.src = 'https://user-images.githubusercontent.com/10379601/29446482-04f7036a-841f-11e7-9872-91d1fc2ea683.png'
        body.appendChild(imgElement)
    
        await new Promise(resolve => {
            imgElement.onload = resolve;
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2021-11-14
      • 2019-12-29
      • 1970-01-01
      相关资源
      最近更新 更多