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
相关推荐
汤姆小白8 小时前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
To_OC13 小时前
手写 AI 编程 Agent 的命令执行工具:我被 child_process 坑出来的实战经验
后端·node.js·agent
向日的葵00615 小时前
langchain的Tools教程(三)
python·langchain·tools
其实防守也摸鱼15 小时前
运维--学习阶段问题解答(1)(自测)
linux·运维·服务器·数据库·学习·自动化·命令模式
言乐616 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
GJGCY16 小时前
财务智能体落地实践:RPA、大模型与规则引擎如何构建业财自动化闭环?
经验分享·ai·自动化·财务·智能体
YUS云生16 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
智写-AI17 小时前
真实有效的免费降英文AI工具服务商
人工智能·python
yuhuofei202117 小时前
【Python入门】了解掌握Python中函数的基本使用
python