蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行全页/视口截图、JPEG/裁剪/透明底选项、元素截图及视频句柄前置检查实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-screenshots-videos.py
explore-screenshots-videos.py169 行
"""Offline Playwright Chromium lab for Chapter 29: Screenshots & Videos."""
import json
import os
from pathlib import Path
import struct
import tempfile
from playwright.sync_api import sync_playwright


PAGE_HTML = """<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <style>
    body { margin: 0; font-family: sans-serif; }
    nav { height: 60px; background: #1e293b; color: #fff; display: flex; align-items: center; padding: 0 16px; }
    #btn { margin: 16px; width: 120px; height: 40px; background: #2563eb; color: #fff; border: none; }
    @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
    #anim { width: 40px; height: 40px; background: #10b981; animation: spin 1s linear infinite; }
    #spacer { height: 1500px; }
  </style>
</head>
<body>
  <nav role="navigation">主导航栏</nav>
  <button id="btn">提交</button>
  <div id="anim"></div>
  <div id="spacer"></div>
</body>
</html>"""


def png_info(data: bytes):
    assert data[:8] == b"\x89PNG\r\n\x1a\n", "not PNG"
    width, height = struct.unpack(">II", data[16:24])
    color_type = data[25]
    return {"width": width, "height": height, "color_type": color_type}


def launch_chromium(p):
    if os.path.exists(p.chromium.executable_path):
        return p.chromium.launch(headless=True)
    for ch in ("chrome", "msedge"):
        try:
            return p.chromium.launch(channel=ch, headless=True)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def make_case(name, expected, actual):
    return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}


def main():
    cases = []
    with tempfile.TemporaryDirectory() as tmpdir:
        tmp = Path(tmpdir)
        with sync_playwright() as p:
            browser = launch_chromium(p)
            try:
                ctx = browser.new_context(viewport={"width": 800, "height": 600})
                pg = ctx.new_page()
                pg.set_content(PAGE_HTML)

                # Case 1: Viewport buffer & full_page=True PNG dimensions
                vp_buf = pg.screenshot()
                full_path = tmp / "full-page.png"
                pg.screenshot(path=str(full_path), full_page=True)
                vp_meta = png_info(vp_buf)
                full_meta = png_info(full_path.read_bytes())
                cases.append(make_case(
                    "viewport_and_full_page_screenshot",
                    {
                        "viewport_dims": [800, 600],
                        "full_width": 800,
                        "full_taller_than_1600": True,
                        "file_exists": True,
                    },
                    {
                        "viewport_dims": [vp_meta["width"], vp_meta["height"]],
                        "full_width": full_meta["width"],
                        "full_taller_than_1600": full_meta["height"] >= 1600,
                        "file_exists": full_path.exists(),
                    },
                ))

                # Case 2: Screenshot options (type='jpeg'+quality, clip, animations='disabled', omit_background=True)
                jpg_bytes = pg.screenshot(type="jpeg", quality=90)
                clip_bytes = pg.screenshot(
                    clip={"x": 0, "y": 0, "width": 400, "height": 300},
                    animations="disabled",
                )
                clip_meta = png_info(clip_bytes)
                pg_trans = ctx.new_page()
                pg_trans.set_content("<body style='margin:0;background:transparent'><div style='width:20px;height:20px;background:red'></div></body>")
                trans_bytes = pg_trans.screenshot(omit_background=True, clip={"x": 0, "y": 0, "width": 40, "height": 40})
                trans_meta = png_info(trans_bytes)
                pg_trans.close()

                cases.append(make_case(
                    "screenshot_options_jpeg_clip_omitbg",
                    {
                        "is_jpeg": True,
                        "clip_dims": [400, 300],
                        "omit_bg_dims": [40, 40],
                        "omit_bg_rgba": True,
                    },
                    {
                        "is_jpeg": jpg_bytes[:3] == b"\xff\xd8\xff",
                        "clip_dims": [clip_meta["width"], clip_meta["height"]],
                        "omit_bg_dims": [trans_meta["width"], trans_meta["height"]],
                        "omit_bg_rgba": trans_meta["color_type"] == 6,
                    },
                ))

                # Case 3: Element locator screenshots (navigation & button)
                nav_bytes = pg.get_by_role("navigation").screenshot()
                btn_bytes = pg.get_by_role("button", name="提交").screenshot()
                nav_meta = png_info(nav_bytes)
                btn_meta = png_info(btn_bytes)
                cases.append(make_case(
                    "element_locator_screenshot",
                    {"nav_dims": [800, 60], "btn_dims": [120, 40]},
                    {
                        "nav_dims": [nav_meta["width"], nav_meta["height"]],
                        "btn_dims": [btn_meta["width"], btn_meta["height"]],
                    },
                ))

                # Case 4: page.video handle when disabled + record_video_dir precondition check
                video_disabled_is_none = pg.video is None
                ctx.close()

                video_dir = tmp / "videos"
                video_dir.mkdir(exist_ok=True)
                vctx = browser.new_context(
                    viewport={"width": 320, "height": 240},
                    record_video_dir=str(video_dir),
                    record_video_size={"width": 320, "height": 240},
                )
                video_check_ok = False
                try:
                    vpg = vctx.new_page()
                    vpg.set_content("<h1>video</h1>")
                    saved_path = tmp / "saved.webm"
                    vobj = vpg.video
                    vctx.close()
                    if vobj is not None:
                        vobj.save_as(str(saved_path))
                        video_check_ok = saved_path.exists() and saved_path.stat().st_size > 0
                except Exception as exc:
                    vctx.close()
                    # Honest check when local Playwright ffmpeg binary is not installed
                    video_check_ok = "ffmpeg" in str(exc).lower()

                cases.append(make_case(
                    "video_handle_and_ffmpeg_precondition",
                    {"video_disabled_is_none": True, "record_video_checked": True},
                    {"video_disabled_is_none": video_disabled_is_none, "record_video_checked": video_check_ok},
                ))
            finally:
                browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/playwright-screenshots-videos-lab/explore-screenshots-videos.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-screenshots-videos.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Playwright

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip

下载课程关联工程包:Playwright

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a631.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习