【问题标题】:Set Width and Height of Element Screenshot in Puppeteer在 Puppeteer 中设置元素屏幕截图的宽度和高度
【发布时间】:2019-03-05 12:00:43
【问题描述】:

如果我有这个代码:

const puppeteer = require('puppeteer');

var test = async () => {
  const browser = await puppeteer.launch({args: ["--no-sandbox", "--disable-setuid-sandbox"]});
  const page = await browser.newPage();
  await page.goto('https://community.wikia.com/wiki/Special:WikiActivity');
  let element =  await page.$('#WikiaMainContent');
  await page.setViewport({ width: 800, height: 1000}); // This is ignored
  await element.screenshot({path: "./wiki.png"});
  await browser.close(); 
}

test();

屏幕截图大于视口。

如何使屏幕截图具有800pxwidth1000pxheight

【问题讨论】:

  • 对不起,这段代码是我凭记忆写的,请检查编辑。
  • 在更正后的代码中,您没有调用主要的 IIFE 函数吗?
  • 我已经正确地测试了这个。它会生成一个新图像,但它仍然太大

标签: javascript node.js google-chrome-devtools screenshot puppeteer


【解决方案1】:

您可以使用elementHandle.screenshot()clip 选项和elementHandle.boundingBox() 一起设置元素屏幕截图的widthheight

下面的例子会截取一个元素,如果元素超出当前视口,则对其进行剪辑:

await page.setViewport({
  width: 800,
  height: 1000,
});

const example = await page.$('#example');
const bounding_box = await example.boundingBox();

await example.screenshot({
  path: 'example.png',
  clip: {
    x: bounding_box.x,
    y: bounding_box.y,
    width: Math.min(bounding_box.width, page.viewport().width),
    height: Math.min(bounding_box.height, page.viewport().height),
  },
});

【讨论】:

    【解决方案2】:

    我有一个更好的解决方案,在前面使用html2canvas:

    https://gist.github.com/homam/3162383c8b22e7af691085e77cdbb414

    或者在后端将它与 puppeteer 和 html2canvas 一起使用:

    const screenshot = await page.evaluate(async () => {
       const canvasElement = await html2canvas($("div")[0], {
            // useCORS: true,
       });
    
       let image = Canvas2Image.convertToImage(
            canvasElement,
            $(canvasElement).width(),
            $(canvasElement).height(),
            "png"
        );
        console.log(image.src)
        return image.src;
    })
    var fs = require('fs');
    // strip off the data: url prefix to get just the base64-encoded bytes
    var data = screenshot.replace(/^data:image\/\w+;base64,/, "");
    var buf = new Buffer(data, 'base64');
    fs.writeFile(`./screenshots/div-${Date.now()}-.png`, buf);
    

    完整代码在这里: https://github.com/davidtorroija/screenshot-of-div-e2e/blob/master/README.md

    这样更好,因为很容易截取一个巨大的div,不需要滚动,你不会丢失div的任何部分

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 2013-01-02
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多