You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright中通过传入坐标和尺寸截取屏幕截图?

如何用Playwright传入坐标和尺寸截取截图

当然可以,Playwright 支持直接传入坐标和尺寸来截取指定区域的截图,不需要必须通过定位器调用screenshot方法。

你可以使用page.screenshot()方法的clip选项,这个选项接受一个包含x、y、width、height的对象,完全匹配getBoundingClientRect()返回的属性结构。

示例1:基于getBoundingClientRect()结果截图

// 获取目标元素的位置和尺寸
const rect = await page.evaluate(() => {
  const elem = document.querySelector('.header');
  return elem.getBoundingClientRect();
});

// 截取指定区域
await page.screenshot({
  path: 'target-screenshot.png',
  clip: {
    x: rect.x,
    y: rect.y,
    width: rect.width,
    height: rect.height
  }
});

示例2:结合定位器更高效的方式

如果已经使用定位器定位了元素,Playwright还提供了locator.boundingBox()方法,直接返回符合clip要求的坐标尺寸对象,无需手动处理:

const headerLocator = page.locator('.header');
const elemBox = await headerLocator.boundingBox();

await page.screenshot({
  path: 'header-screenshot.png',
  clip: elemBox
});

这种方式比直接用evaluate更可靠,因为Playwright会自动处理元素的动态位置变化,确保获取到最新的坐标和尺寸。

内容的提问来源于stack exchange,提问作者GorvGoyl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:01:27