browser-use 库网页自动化截图

目录

代码

python 复制代码
import asyncio
import base64
import os
from datetime import datetime

import pytest

from browser_use.browser.browser import Browser, BrowserConfig

async def test_take_full_page_screenshot():
    browser = Browser(config=BrowserConfig(
        browser_instance_path=r"C:\Program Files\Google\Chrome\Application\chrome.exe",
        headless=False, disable_security=True))

    async with await browser.new_context() as context:
        page = await context.get_current_page()
        # Go to a test page
        await page.goto('https://www.google.com')

        await asyncio.sleep(3)
        # Take full page screenshot
        screenshot_b64 = await context.take_screenshot(full_page=True)
        await asyncio.sleep(3)
        
        # 创建screenshots目录(如果不存在)
        screenshots_dir = os.path.join(os.path.dirname(__file__), 'screenshots')
        os.makedirs(screenshots_dir, exist_ok=True)
        
        # 生成带时间戳的文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        screenshot_path = os.path.join(screenshots_dir, f'screenshot_{timestamp}.png')
        
        # 将base64字符串解码并保存为图片文件
        with open(screenshot_path, 'wb') as f:
            f.write(base64.b64decode(screenshot_b64))
        
        print(f'Screenshot saved to: {screenshot_path}')

        # Verify screenshot is not empty and is valid base64
        assert screenshot_b64 is not None
        assert isinstance(screenshot_b64, str)
        assert len(screenshot_b64) > 0

        # Test we can decode the base64 string
        try:
            base64.b64decode(screenshot_b64)
        except Exception as e:
            pytest.fail(f'Failed to decode base64 screenshot: {str(e)}')

    await browser.close()

if __name__ == '__main__':
    asyncio.run(test_take_full_page_screenshot())

代码解释

  1. 导入必要模块:
python 复制代码
import asyncio  # 用于异步操作
import base64   # 用于处理base64编码的图片数据
import os       # 用于文件和目录操作
from datetime import datetime  # 用于生成时间戳
  1. 测试函数定义:
python 复制代码
async def test_take_full_page_screenshot():

这是一个异步测试函数,用于测试网页截图功能。

  1. 浏览器初始化:
python 复制代码
browser = Browser(config=BrowserConfig(
    browser_instance_path=r"C:\Program Files\Google\Chrome\Application\chrome.exe",
    headless=False,  # 显示浏览器界面
    disable_security=True))  # 禁用安全限制
  1. 页面操作:
  • 创建新的浏览器上下文
  • 打开谷歌首页
  • 等待3秒让页面加载
  • 获取全页面截图(base64格式)
  1. 截图保存流程:
python 复制代码
# 创建保存目录
screenshots_dir = os.path.join(os.path.dirname(__file__), 'screenshots')
os.makedirs(screenshots_dir, exist_ok=True)

# 生成文件名(使用时间戳)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
screenshot_path = os.path.join(screenshots_dir, f'screenshot_{timestamp}.png')

# 保存图片
with open(screenshot_path, 'wb') as f:
    f.write(base64.b64decode(screenshot_b64))
  1. 验证步骤:
  • 检查截图数据不为空
  • 验证数据类型是字符串
  • 确保数据长度大于0
  • 测试能否正确解码base64数据
  1. 程序入口:
python 复制代码
if __name__ == '__main__':
    asyncio.run(test_take_full_page_screenshot())

使用 asyncio.run() 运行异步测试函数

这个脚本的主要目的是:

  1. 自动化测试网页截图功能
  2. 保存截图到本地文件
  3. 验证截图数据的有效性
  4. 提供可重复的测试用例

运行后会在脚本所在目录下创建 screenshots 文件夹,并保存带时间戳的PNG格式截图。

执行效果

bash 复制代码
python screenshot_test.py
INFO     [browser_use] BrowserUse logging setup complete with level info
INFO     [root] Anonymized telemetry enabled. See https://docs.browser-use.com/development/telemetry for more information.
Screenshot saved to: D:\llm\browser-use-test\browser-use\screenshots\screenshot_20250326_234705.png
相关推荐
奈落242 小时前
AI辅助的另一面:从2026年国际AI安全报告的“故障”清单到国内专家的可靠性短板,自主行动的Agent为什么更难及时干预
人工智能·安全·agent·本地部署·ai 办公
实名上网宋凯宣5 小时前
Django
后端·python·django
镜子AI6 小时前
镜子AI 技术复盘:三条自动化链路上的“停止条件“设计
运维·人工智能·自动化
如若1236 小时前
【论文复现】CoFailMed:从零复现医学图像分割的共享失败审计,含完整代码流程与科研绘图
人工智能·python
砚底藏山河8 小时前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融
视觉小萌新8 小时前
AI Class 3 · Chapter 1:变量、字符串、list/dict、if/for(python学习-小白版-有经验可跳过)
python·学习·list
薛定谔的猫-菜鸟程序员9 小时前
软件架构设计师开发资料大全(从入门到精通)
后端·python·系统架构·flask·架构设计师
时早玖沐10 小时前
放弃 QQ 官方机器人:用 SnowLuma + AstrBot 自建 QQ 机器人
docker·开源·agent
Ramble_Naylor10 小时前
Rust深度解读:Send 与 Sync 的本质与线程安全边界
python·算法·rust
nujnewnehc10 小时前
给记事软件加上 mcp
agent·mcp