The strongest automated testing framework Playwright (10) - Screenshot

screenshot

Capture a screenshot and save it to a file:

page.screenshot(path="screenshot.png")

 Screenshots can be saved as 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)

Screenshot API accepts many parameters for image format, clipping area, quality, etc. Be sure to check them out.

full page screenshot

A full page screenshot is a screenshot of a complete scrollable page, as if you had a very tall screen and the page would fit perfectly on it.

page.screenshot(path="screenshot.png", full_page=True)

capture to buffer

Instead of writing to a file, you can take a buffer with an image and post-process it or pass it to a third-party pixel diff tool.

Convert to base64 encoding

screenshot_bytes = page.screenshot()
print(base64.b64encode(screenshot_bytes).decode())

element screenshot

Sometimes it is useful to take a screenshot of a single element.

page.locator(".header").screenshot(path="screenshot.png")
page.locator("#kw").screenshot(path="header.png")

 Only intercept Baidu text box

 

 

Guess you like

Origin blog.csdn.net/seanyang_/article/details/132249752