Skip to content

About

AI Browser Automation Mastery Skill - Master browser automation workflows using Playwright CLI and Agent Browser. Covers web scraping, auto-publishing, form filling, web app testing, and 0-TOKEN script optimization.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

🤖 AI 浏览器自动化精通

Master Browser Automation Workflows with AI

GitHub stars GitHub forks GitHub issues GitHub last commit License

使用 Playwright CLI 和 Agent Browser 掌握浏览器自动化工作流

网页抓取 · 自动发布 · 表单填写 · Web 测试 · 0-TOKEN 脚本优化

🚀 快速开始 · 📖 使用指南 · 💡 实战案例 · ❓ 常见问题 · 🤝 参与贡献


📋 目录


✨ 核心优势

🧠 无需专业知识

通过自然语言即可操作浏览器,无需掌握底层 API 和 CSS 选择器

💰 TOKEN 消耗极低

Playwright CLI 相比传统 MCP 方案减少约 4 倍 TOKEN 消耗

📸 上下文优化

通过按需读取网页快照和本地截图,大幅降低上下文消耗

🚀 0-TOKEN 运行

固定流程可生成独立脚本,完全不需要 AI 参与即可运行


🎯 适用场景

场景 说明 难度
🛒 电商评论抓取 抓取商品评论并导出 CSV ⭐
📝 文章自动发布 Markdown/HTML 内容发布到各平台 ⭐⭐
🧪 Web APP 自动化测试 自动执行测试用例,验证功能完整性 ⭐⭐
📋 表单批量填写 自动填写并提交网页表单 ⭐
📊 数据采集监控 定时抓取网页数据变化 ⭐⭐
🔄 RPA 流程替代 替代传统桌面自动化工具 ⭐⭐⭐

🚀 快速开始

环境准备清单

□ Node.js 已安装    → node --version
□ Playwright CLI    → npx playwright --version
□ Chrome/Edge 浏览器 → 已安装

安装 Playwright CLI

# 方式 1:通过 npm 安装(推荐)
npm install -g playwright

# 方式 2:Python 用户通过 pip 安装
pip install playwright
python -m playwright install chromium

# 验证安装
npx playwright --version   # 或 python -m playwright --version

验证环境

# 打开一个网页测试
playwright open https://example.com --headed

# 截取页面快照
playwright snapshot

# 截图保存
playwright screenshot test.png

🛠️ 技术方案

方案 A:Playwright CLI(推荐)

微软开源的命令行浏览器自动化工具,TOKEN 消耗最低。

# 基础操作
playwright open https://example.com --headed      # 打开网页
playwright snapshot                                 # 获取页面摘要
playwright click "#submit-btn"                     # 点击元素
playwright type "#email" "user@example.com"        # 输入文字
playwright screenshot output.png                   # 截图

核心参数:

参数 说明
--headed 使用有头浏览器(默认无头)
--profile <name> 持久化存储 cookie/登录状态
--viewport <WxH> 设置视口大小
--wait-for <selector> 等待特定元素出现
--timeout <ms> 超时时间(毫秒)
-o, --output 截图或输出文件路径

方案 B:Agent Browser CLI(内置)

Agent 框架内置的浏览器自动化工具,开箱即用。

# 基础操作
agent-browser open "https://example.com"            # 打开网页
agent-browser snapshot                              # 获取页面快照
agent-browser click "#button" --text "提交"          # 点击元素
agent-browser type "#input" "内容"                   # 输入文本
agent-browser screenshot --path screenshot.png      # 截图
agent-browser close --all                           # 关闭所有窗口

📊 方案对比

特性 Playwright CLI Agent Browser
TOKEN 消耗 🟢 极低(~4x 更优) 🟡 中等
安装依赖 需 Node.js + npm 🟢 内置即用
调试体验 🟢 --headed 可视化好 🟡 需配合截图
跨平台 🟢 全平台支持 🟡 主要 Windows
登录持久化 🟢 --profile 参数 🟡 需手动处理
适用场景 固定流程脚本化 AI 即时探索任务

📖 使用指南

五步工作流

┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│  Step 1     │     │  Step 2     │     │  Step 3     │
│  环境准备   │ ──▶ │  AI 探索    │ ──▶ │  提炼 Skill │
│  (安装工具) │     │  (首次任务) │     │  (降本 10x) │
└─────────────┘     └─────────────┘     └─────────────┘
                                              │
                                              ▼
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│  Step 5     │     │  Step 4     │     │             │
│  全自动     │ ◀── │  生成脚本   │ ◀── │  重复执行   │
│  (定时任务) │     │  (0 TOKEN)  │     │  (验证)     │
└─────────────┘     └─────────────┘     └─────────────┘

Step 1: 环境准备

node --version          # 检查 Node.js
npx playwright --version  # 检查 Playwright

Step 2: 让 AI 自主探索

  • 用自然语言描述目标(如「打开抖音首页并截取页面」)
  • AI 会自主摸索页面结构、尝试操作
  • 记录遇到的问题和解决方案

⚠️ 首次探索 TOKEN 消耗较高(约 40%),这是正常的投入成本。

Step 3: 提炼为 Skill(降本 10x)

  • 记录正确的选择器和操作顺序
  • 标注常见坑点和 workaround
  • 编写参考文档放入 references/

效果:二次执行相同类型任务,TOKEN 消耗从 ~41% 降至 ~5%

Step 4: 生成固定脚本(0 TOKEN)

# PowerShell 示例
$browser = Start-Process chrome -ArgumentList "https://target-site.com/product/123"
Start-Sleep -Seconds 3
# ... Playwright CLI 操作 ...
Export-Csv -Path "comments.csv" -NoTypeInformation

Step 5: 结合定时任务实现全自动

  • 使用定时任务配置定期触发
  • 脚本独立运行,完全不需要 AI 参与
  • 结果通过微信/邮件通知

💡 实战案例

案例 1: 商品评论抓取

目标: 抓取某商品前 100 条评论并保存为 CSV

"""
电商商品评论抓取器
用法: python scrape_comments.py <商品URL> [数量]
"""
from playwright.sync_api import sync_playwright

def scrape_comments(url, target_count=100):
    comments = []
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()
        
        # 打开商品页
        page.goto(url, wait_until="networkidle", timeout=30000)
        
        # 点击评价 Tab
        page.click("text=评价", timeout=5000)
        page.wait_for_load_state("networkidle")
        
        # 循环加载并提取评论
        for _ in range(20):
            items = page.query_selector_all(".review-item")
            for item in items:
                username = item.query_selector(".user-name").inner_text()
                content = item.query_selector(".content").inner_text()
                comments.append({"user": username, "text": content})
            
            # 滚动加载更多
            page.evaluate("window.scrollBy(0, window.innerHeight * 2)")
        
        browser.close()
    return comments

CSV 输出格式:

用户名,评分,评论内容,时间
张三,5,"质量很好",2026-04-17
李四,4,"性价比高",2026-04-16

案例 2: Markdown 文章自动发布

问题: 目标平台不支持直接粘贴 Markdown(格式错乱、图片丢失)

解决方案:

"""
Markdown 文章预处理器 — 将远程图片下载到本地
"""
import re
import urllib.request

def process_markdown(md_path, output_dir):
    with open(md_path, "r", encoding="utf-8") as f:
        content = f.read()
    
    # 匹配所有图片链接
    img_pattern = r'!\[([^\]]*)\]\(([^)]+)\)'
    images = re.findall(img_pattern, content)
    
    for i, (alt, url) in enumerate(images, 1):
        # 下载图片到本地
        filename = f"{i:03d}.png"
        download_image(url, f"{output_dir}/images/{filename}")
        
        # 替换图片路径
        content = content.replace(url, f"./images/{filename}")
    
    # 保存处理后的 Markdown
    with open(f"{output_dir}/article.md", "w") as f:
        f.write(content)

Playwright 发布流程:

# 打开平台后台
playwright open https://platform.com/admin --profile my-session --headed

# 新建文章
playwright click "#new-article-btn"

# 输入标题
playwright type "#title" "我的文章标题"

# 粘贴 HTML 内容
playwright evaluate "document.querySelector('#editor').innerHTML = \`<p>内容...</p>\`"

# 上传图片
playwright upload-file "#image-upload" "./images/001.png"

# 发布
playwright click "#publish-btn"

案例 3: Web APP 自动化测试

测试用例 JSON:

{
  "name": "用户登录流程测试",
  "steps": [
    {"action": "open", "path": "/"},
    {"action": "click", "selector": "#login-btn"},
    {"action": "type", "selector": "#email", "value": "test@example.com"},
    {"action": "type", "selector": "#password", "value": "pass123"},
    {"action": "click", "selector": "#submit"},
    {"action": "assert-visible", "selector": ".dashboard"},
    {"action": "screenshot"}
  ]
}

PowerShell 测试执行器:

param([string]$TestFile, [string]$BaseUrl = "http://localhost:3000")

$tests = Get-Content $TestFile | ConvertFrom-Json
foreach ($test in $tests) {
    Write-Host "▶ 测试: $($test.name)" -ForegroundColor Yellow
    
    foreach ($step in $test.steps) {
        switch ($step.action) {
            "open"              { playwright open "$BaseUrl$($step.path)" --headed }
            "click"             { playwright click $step.selector }
            "type"              { playwright type $step.selector $step.value }
            "assert-visible"    { $s = playwright snapshot; if ($s -match $step.selector) { "✓ PASS" } else { throw "FAIL" } }
            "screenshot"        { playwright screenshot -o "test-results/$($test.name).png" }
        }
    }
}

📊 效率优化金字塔

                        ╱╲
                       ╱TOKEN╲
                      ╱  ~0%  ╲
                     ╱─────────╲
                    ╱  Level 4  ╲
                   ╱  固定脚本   ╲
                  ╱  独立运行    ╲
                 ╱───────────────╲
                ╱    Level 3      ╲
               ╱    5% (Skill)    ╲
              ╱   经验固化后的 Skill ╲
             ╱─────────────────────╲
            ╱       Level 2         ╲
           ╱    25% (Agent Browser)  ╲
          ╱      内置浏览器工具        ╲
         ╱───────────────────────────╲
        ╱          Level 1            ╲
       ╱     ~100% (首次纯AI探索)      ╲
      ╱      无任何预设知识              ╲
     ╱═══════════════════════════════════╲

优化原则: 任务越固定,越应该向下层迁移。

阶段 TOKEN 消耗 说明
首次纯 AI 探索 ~41% 无任何预设,AI 自主摸索
加入 Skill 后 ~5% 经验固化,跳过探索阶段
固定脚本运行 0% 独立执行,无需 AI 参与

❓ 常见问题排查

问题 解决方案
🔴 Chrome 启动冲突 先 taskkill /F /IM chrome.exe 再启动 agent-browser
🔴 页面加载超时 增加 --timeout 或使用 wait --load networkidle
🔴 元素找不到 用 snapshot 检查当前 DOM,确认选择器正确
🔴 登录态失效 使用 --profile 持久化 cookie
🟡 动态渲染内容空白 等待 AJAX 完成后再 snapshot
🟡 反爬检测拦截 --headed 模式 + 降低操作频率
🟡 中文编码乱码 设置 $env:PYTHONIOENCODING='utf-8'
🟡 SSL 证书错误 配置代理时加 --ignore-https-errors 或走系统代理

📚 参考资料

文件 说明
references/api_reference.md Playwright CLI 完整 API 参考
references/cases.md 详细实战案例和完整脚本模板
SKILL.md 完整的技能定义文档

🤝 参与贡献

欢迎提交 Issue 和 Pull Request!

如何贡献

  1. Fork 本仓库
  2. 创建 功能分支 (git checkout -b feature/amazing-feature)
  3. 提交 更改 (git commit -m 'Add some amazing feature')
  4. 推送 到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

贡献方向

  • 📝 补充更多实战案例
  • 🐛 修复已知问题
  • ✨ 添加新的自动化场景
  • 📖 完善文档和教程
  • 🧪 添加测试用例

📄 许可证

本项目采用 MIT License 开源协议。


⭐ 如果觉得有用,请点个 Star 支持一下!

Made with ❤️ by Delight0628

About

AI Browser Automation Mastery Skill - Master browser automation workflows using Playwright CLI and Agent Browser. Covers web scraping, auto-publishing, form filling, web app testing, and 0-TOKEN script optimization.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors