在截图上增加附加文字,比如一个时间戳,一段说明文字

102 阅读1分钟

为了更好的佐证,可以在截图上增加时间戳,这样我们的证据会显得更有说服力

from playwright.sync_api import sync_playwright

def screenshot_with_label(url, output_path, label_text):
    with sync_playwright() as p:
        # 启动浏览器
        browser = p.chromium.launch(headless=False)
        context = browser.new_context()
        page = context.new_page()

        # 导航到目标页面
        page.goto(url)

        # 确保页面加载完成
        page.wait_for_load_state("networkidle")

        # 动态添加标签文字
        page.add_script_tag(
            content=f"""
            const label = document.createElement('div');
            label.style.position = 'fixed';
            label.style.top = '10px';
            label.style.left = '10px';
            label.style.zIndex = '99999';
            label.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
            label.style.color = 'white';
            label.style.padding = '5px';
            label.style.fontSize = '16px';
            label.style.borderRadius = '5px';
            label.textContent = '{label_text}';
            document.body.appendChild(label);
            """
        )

        # 对整个页面进行截图
        page.screenshot(path=output_path)

        # 关闭浏览器
        browser.close()

# 示例调用
url = "https://example.com"
output_path = "screenshot_with_label.png"
label_text = "This is a label"
screenshot_with_label(url, output_path, label_text)