Puppeteer Page.screenshot 截屏页面中的一个区域

25 min read

使用Puppeteer的Page.screenshot方法,可以截取整个页面的屏幕截图。如果要截取页面中的特定区域,可以通过设置clip选项来指定截取区域的位置和大小。

下面是一个使用Puppeteer截取特定区域的示例代码:

const puppeteer = require('puppeteer');

async function run() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  
  await page.goto('https://example.com');
  
  // 获取元素的位置和大小
  const element = await page.$('#myElement');
  const boundingBox = await element.boundingBox();
  
  // 使用元素的位置和大小来指定截取区域
  await page.screenshot({
    path: 'screenshot.png',
    clip: {
      x: boundingBox.x,
      y: boundingBox.y,
      width: boundingBox.width,
      height: boundingBox.height
    }
  });
  
  await browser.close();
}

run();

在上面的示例代码中,首先通过page.$方法获取元素的句柄,然后使用boundingBox方法获取元素的位置和大小。接下来,通过设置clip选项来指定要截取的区域。最后,使用page.screenshot方法来截取页面的屏幕截图,并将截图保存为screenshot.png文件。

请注意,clip选项的位置和大小是相对于整个页面的坐标,如果需要截取嵌套在iframes或其他框架中的元素,请先切换到相应的框架。