截图
捕获屏幕截图并将其保存到文件中:
page.screenshot(path="screenshot.png")
可将页面截图保存为screen.png
import os
from playwright.sync_api import Playwright, expect, sync_playwright
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()
page.goto("http:www.baidu.com")
page.screenshot(path="screenshot.png")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
屏幕截图API接受图像格式,剪辑区域,质量等的许多参数。请务必检查它们。
- 整页截图
- 捕获到缓冲区
- 元素截图
整页截图
整页屏幕截图是完整可滚动页面的屏幕截图,就好像您有一个非常高的屏幕并且页面可以完全适合它一样。
page.screenshot(path="screenshot.png", full_page=True)
捕获到缓冲区
您可以获取带有图像的缓冲区并对其进行后处理或将其传递给第三方像素差异工具,而不是写入文件。
转为base64编码
screenshot_bytes = page.screenshot()
print(base64.b64encode(screenshot_bytes).decode())
元素截图
有时,截取单个元素的屏幕截图很有用。
page.locator(".header").screenshot(path="screenshot.png")
page.locator("#kw").screenshot(path="header.png")
只截取百度文本框