无法使用puppeteer截取屏幕截图,它会转储空图像文件

问题描述 投票:2回答:1

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

<!doctype html>
<html>

<head>
</head>

<body>
</body>

</html>

然后我有另一个文件旨在打开chrome无头的上述文件,在其中添加一个图像,然后截取它,看看:

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个回答
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;
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.