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
相关推荐
xiezhr2 分钟前
现在的豆包跟以前不一样了
人工智能·ai·agent·ai agent·豆包
言乐63 分钟前
Python关于老游复刻与创新2
前端·javascript·css·python·css3
挨踢诗人2 小时前
金蝶K3 WISE × 乐企平台 直连数电票集成解决方案(商贸企业开票自动化)
大数据·运维·自动化
青 春 记 忆8 小时前
Dify Docker Compose 通用无损升级指南:从备份、双版本预演到切换与回滚
运维·人工智能·python·docker·容器
GlueNa2SiO38 小时前
03-Flask模板引擎Jinja2详解
笔记·python·flask
魔术师Grace8 小时前
Agent总出错,什么时候才该训练模型?
llm·agent·强化学习
神奇霸王龙10 小时前
Cursor 3 + Claude Opus 4.8 屠榜:5 编程基座 IDE 卡位
ide·人工智能·ai·aigc·agent·ai编程·ai写作
临沂GEO11 小时前
GEO搜索优化科普|正规地理位置流量运营入门指南
大数据·人工智能·python·流量运营
大模型码小白11 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
冬奇Lab12 小时前
Code Agent 解剖(12):Harness 设计之二——上下文工程
人工智能·开源·agent