在Puppeteer中设置元素屏幕截图的宽度和高度

时间:2018-09-29 22:36:36

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

如果我有此代码:

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();

屏幕截图大于视口。

如何使屏幕快照的width800px,而height1000px

3 个答案:

答案 0 :(得分:6)

您可以将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),
  },
});

答案 1 :(得分:0)

您可以简单地使用:

  await page.screenshot({path: "./wiki.png"});

代替

  await element.screenshot({path: "./wiki.png"});

答案 2 :(得分:-1)

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

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

或与后端中的puppeteer和html2canvas一起使用:

class MyWidget extends StatelessWidget {

  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: _someFuture,
      builder: (ctx, snapshot) {
        // can also check for snapshot.hasData or snapshot.hasError to
        // provide more user feedback eg.
        if(snapshot.connectionState == ConnectionState.done) 
          return Text('${snapshot.data}');        
        return Text('No data available yet...');
      }
    );
  }

}

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

这更好,因为它很容易为一个巨大的div拍摄屏幕快照,并且无需滚动,并且您不会丢失div的任何部分