puppeteer:无需单独下载即可获取 base64 编码图像

puppeteer: Get base64 encoded image without separate download

在不支持下载图片或在新标签页中打开图片的页面上,我可以使用 Chrome 开发人员(工具 -> 网络)右键单击图片并执行 "copy image as URI"。

是否可以对 puppeteer 做同样的事情?

我尝试使用几个 Node.js 模块来将图像转换为其 base64 表示形式,但它们似乎都先下载图像,然后 return base64 表示形式。

是的,您可以使用 response.buffer() to get the buffer of a resource. You can then turn the buffer into a base64-encoded string by using buffer.toString('base64')

代码示例

以下示例转到 google.com 网站,等待第一个 PNG 资源,然后打印其 base64 编码的图像。

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    const [response] = await Promise.all([
        page.waitForResponse(response => response.url().includes('.png')),
        page.goto('https://www.google.com/')
    ]);
    const buffer = await response.buffer();
    console.log('data:image/png;base64,' + buffer.toString('base64'));

    await browser.close();
})();

此代码示例等待单个资源。或者,您可以收听 response 事件以同样的方式下载多张图片。

另一个解决方案是:

const base64 = await page.screenshot({ encoding: "base64" })

以下对我有用

  let screenshot = await page.screenshot({ encoding: "base64" }).then(function(data){
            let base64Encode = `data:image/png;base64,${data}`;
            return base64Encode;
    });

您可以在 addcontext 中使用它 - 它会添加到 mochareport

addContext(this, {
    title: 'screenshot ',
    value: global.backEndData.contactCountTotalImage,
  });