编程 万字深度解析:阿里 Page Agent——纯 JS GUI Agent 如何用一行代码颠覆 Web 自动化——从 DOM 脱水到 MCP 集成的生产级实战(2026)

2026-07-01 01:45:01 +0800 CST views 10

万字深度解析:阿里 Page Agent——纯 JS GUI Agent 如何用一行代码颠覆 Web 自动化——从 DOM 脱水到 MCP 集成的生产级实战(2026)

2026年6月,阿里巴巴开源 Page Agent,这是一个纯 JavaScript 实现的页面内嵌式 GUI Agent。与传统浏览器自动化工具完全不同,它不是爬虫或脚本工具,而是面向网站开发者的 SDK——把 AI Agent 直接嵌入到你的 Web 产品中,让用户用自然语言操作网页。本文万字深度解析其技术架构、DOM 脱水算法、安全模型、MCP 集成,以及在 SaaS Copilot、遗留系统现代化、无障碍增强等场景的生产级实战。

一、背景:为什么 Web 自动化需要新思路

1.1 传统方案的困境

过去几年,AI Agent 领域最热门的方向是让 AI 操作整个电脑/浏览器——截图、分析、点击。但这条路的代价很高:

基于视觉的方案(截图 + 多模态模型)

  • 每次交互需要多张截图 → token 消耗巨大
  • 页面布局稍有变化,模型就会"失明"
  • 需要完整的浏览器环境(无头浏览器/Selenium/Playwright)
  • 对于普通用户,需要安装插件或配置 Python 环境

基于 API 的方案(后端爬虫)

  • 需要模拟登录、处理验证码、管理 Cookie
  • 目标网站改版就要重写爬虫逻辑
  • 法律风险:未经授权的自动化访问可能违反服务条款

对于开发者来说,这两条路都有问题:我想在自己的 Web 产品里加 AI 能力,而不是写爬虫或自动化脚本。

1.2 Page Agent 的核心洞察

Page Agent 团队提出了一个关键问题:为什么不直接在网页里运行 Agent?

传统思路:AI 在外部 → 控制浏览器 → 操作网页
Page Agent:AI 在内部 → 直接操作 DOM → 自然语言交互

这个思路的转变带来了根本性的优势:

  • 零门槛集成:一行 <script> 标签或一个 npm install
  • 零后端依赖:所有逻辑在浏览器里运行
  • 精确 DOM 操作:不需要截图,不需要多模态模型
  • 安全可控:内置操作白名单、数据脱敏、知识规则引擎

二、核心架构:DOM 脱水与文本化交互

2.1 为什么不用视觉方案

传统的 GUI Agent(如 Browser-use、OpenAI Operator)采用计算机视觉方案:

  1. 定时截取浏览器窗口截图
  2. 将截图发送给多模态大模型(如 GPT-4V)
  3. 模型分析截图,判断当前页面状态
  4. 模型输出操作指令(如"点击坐标 x=350, y=220 的按钮")

这种方法的问题:

# 视觉方案的代价(伪代码示例)
def visual_automation_step():
    screenshot = browser.capture_screenshot()  # 1张截图 = ~200KB
    model_response = vision_model.analyze(
        image=screenshot,
        prompt="What should I click to login?"
    )
    # GPT-4V 处理一张截图 = ~1000+ tokens
    # 如果一个任务需要10步 = 10张截图 × 10次API调用 = $0.1+ 美元

Page Agent 选择基于 DOM 的文本方案,因为:

  1. 网页本身就是结构化数据,DOM 树已经包含了所有语义信息
  2. 纯文本传输比图片小 10-100 倍
  3. 基于 DOM 的操作更精确,不受渲染样式影响

2.2 DOM 脱水算法(DOM Dehydration)

Page Agent 的核心技术是 DOM 脱水:将复杂的 HTML DOM 树压缩为 AI 可以高效处理的精简文本表示。

<!-- 原始网页 DOM(可能几千个元素) -->
<!DOCTYPE html>
<html>
  <div class="header-wrapper sticky top-0 z-50">
    <nav class="flex items-center justify-between px-6 py-4">
      <div class="logo-container flex-shrink-0">
        <a href="/" class="text-xl font-bold text-blue-600">MyApp</a>
      </div>
      <div class="nav-items flex gap-4 items-center">
        <a href="/about" class="nav-link hover:text-blue-500">About</a>
        <a href="/pricing" class="nav-link">Pricing</a>
        <button class="btn-primary px-4 py-2 rounded">Sign Up</button>
      </div>
    </nav>
  </div>
  <!-- 下方还有 hundreds of elements... -->
</html>
// Page Agent 的 DOM 脱水结果(精简表示)
{
  "elements": [
    {
      "id": "el-1",
      "role": "link",
      "text": "About",
      "action": "click",
      "attrs": { "href": "/about", "class": "nav-link hover:text-blue-500" }
    },
    {
      "id": "el-2", 
      "role": "link",
      "text": "Pricing",
      "action": "click",
      "attrs": { "href": "/pricing" }
    },
    {
      "id": "el-3",
      "role": "button",
      "text": "Sign Up",
      "action": "click",
      "attrs": { "class": "btn-primary" }
    }
  ]
}

脱水算法的工作原理

// DOM 脱水的简化实现逻辑
function dehydrateDOM(root: HTMLElement): DehydratedElement[] {
  const elements: DehydratedElement[] = [];
  
  function traverse(node: Node) {
    if (node.nodeType !== Node.ELEMENT_NODE) return;
    
    const el = node as HTMLElement;
    
    // 跳过隐藏和装饰性元素
    if (isHidden(el) || isDecoration(el)) return;
    
    // 提取可交互元素
    if (isInteractive(el)) {
      elements.push({
        id: generateId(el),
        role: getSemanticRole(el),      // button, link, input, select 等
        text: getAccessibleText(el),    // 无障碍文本
        action: inferAction(el),        // click, type, select 等
        attrs: extractKeyAttrs(el),     // href, type, placeholder 等
      });
    }
    
    // 递归处理子元素
    el.childNodes.forEach(traverse);
  }
  
  traverse(root);
  return elements;
}

function isInteractive(el: HTMLElement): boolean {
  const interactiveRoles = [
    'button', 'link', 'menuitem', 'tab', 'checkbox', 
    'radio', 'textbox', 'combobox', 'switch'
  ];
  
  if (el.tagName === 'A' || el.tagName === 'BUTTON') return true;
  if (el.getAttribute('contenteditable') === 'true') return true;
  
  const role = el.getAttribute('role');
  if (role && interactiveRoles.includes(role)) return true;
  
  const inputTypes = ['text', 'email', 'password', 'search', 'submit', 'reset'];
  if (el.tagName === 'INPUT' && inputTypes.includes(el.type)) return true;
  
  return false;
}

2.3 脱水策略的三大优化

① 语义角色识别

传统 DOM 操作依赖 idCSS selector,但这些经常变化。Page Agent 使用语义角色:

// 传统方案(脆弱)
document.querySelector('#login-form > div:nth-child(3) > button.btn-submit')

// Page Agent 方案(语义稳定)
// 识别 role="button", aria-label="提交登录"

② 分层信息提取

function getAccessibleText(el: HTMLElement): string {
  // 优先级:aria-label > aria-labelledby > textContent > placeholder
  const ariaLabel = el.getAttribute('aria-label');
  if (ariaLabel) return ariaLabel;
  
  const ariaLabelledby = el.getAttribute('aria-labelledby');
  if (ariaLabelledby) {
    return document.getElementById(ariaLabelledby)?.textContent || '';
  }
  
  // 过滤掉隐藏文本和装饰性文本
  if (!isHidden(el) && !isDecoration(el)) {
    return el.textContent?.trim() || el.getAttribute('placeholder') || '';
  }
  
  return '';
}

③ 上下文感知的操作推断

function inferAction(el: HTMLElement): ActionType {
  switch (el.tagName) {
    case 'A': return 'click';        // 链接导航
    case 'BUTTON': return 'click';   // 按钮点击
    case 'INPUT': {
      const type = el.type;
      if (type === 'submit' || type === 'button') return 'click';
      return 'type';                 // 文本输入
    }
    case 'SELECT': return 'select';  // 下拉选择
    case 'TEXTAREA': return 'type';  // 多行文本
    case 'CHECKBOX': return 'check'; // 复选框
    case 'RADIO': return 'radio';    // 单选按钮
  }
  
  // contenteditable 区域
  if (el.getAttribute('contenteditable') === 'true') return 'type';
  
  // 默认双击尝试(可能是特殊组件)
  return 'click';
}

三、系统架构:从初始化到执行的完整流程

3.1 整体架构图

┌─────────────────────────────────────────────────────┐
│                    Web 页面 (你的产品)                  │
│  ┌─────────────────────────────────────────────┐   │
│  │              Page Agent SDK                    │   │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐  │   │
│  │  │DOM 脱水器 │  │ 操作执行器 │  │ 安全引擎  │  │   │
│  │  └────┬─────┘  └────┬─────┘  └────┬─────┘  │   │
│  │       │             │             │         │   │
│  │       ▼             ▼             ▼         │   │
│  │  ┌─────────────────────────────────────┐    │   │
│  │  │         脱水后的结构化 DOM 数据          │    │   │
│  │  └─────────────────────────────────────┘    │   │
│  └─────────────────────────────────────────────┘   │
│                          │                         │
│                          ▼                         │
│              ┌───────────────────┐               │
│              │    LLM API 调用     │  (自备或代理)  │
│              │  (OpenAI/Anthropic │               │
│              │   通义/Qwen 等)     │               │
│              └───────────────────┘               │
└─────────────────────────────────────────────────────┘

3.2 初始化与配置

// 方式一:NPM 安装(生产推荐)
import { PageAgent } from 'page-agent';

const agent = new PageAgent({
  model: 'qwen3.5-plus',           // 任意兼容 OpenAI API 的模型
  baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
  apiKey: process.env.API_KEY,       // 你的 API Key
  language: 'zh-CN',                 // 界面语言
  
  // 可选:高级配置
  maxSteps: 20,                      // 最大操作步数
  temperature: 0.7,                  // 模型温度
  timeout: 30000,                    // 超时时间(ms)
});

// 在页面上显示操作面板
agent.panel.show();
<!-- 方式二:CDN 一行引入(快速测试) -->
<script 
  src="https://cdn.jsdelivr.net/npm/page-agent@latest/dist/iife/page-agent.demo.js"
  crossorigin="true">
</script>
// 方式三:控制台快速体验(无需配置)
// 在浏览器控制台执行:
(function(){
  var s = document.createElement('script');
  s.src = 'https://registry.npmmirror.com/page-agent/1.8.2/files/dist/iife/page-agent.demo.js';
  s.crossorigin = 'true';
  document.head.appendChild(s);
})();

3.3 从指令到操作的完整执行流程

// Page Agent 执行流程的伪代码实现
class PageAgent {
  private llm: LLMClient;
  private security: SecurityEngine;
  
  async execute(instruction: string): Promise<ExecutionResult> {
    // Step 1: 获取脱水后的 DOM
    const dom = this.dehydratePage();
    
    // Step 2: 构建提示词
    const prompt = this.buildPrompt(instruction, dom);
    
    // Step 3: 调用 LLM 获取操作序列
    const plan = await this.llm.complete(prompt);
    
    // Step 4: 逐条执行操作(Human-in-the-Loop)
    for (const step of plan.steps) {
      // 安全检查
      const allowed = await this.security.check(step);
      if (!allowed) {
        return { success: false, reason: 'Action blocked by security policy' };
      }
      
      // 用户确认(如需要)
      if (step.requiresConfirmation) {
        const confirmed = await this.panel.askUser(step);
        if (!confirmed) {
          return { success: false, reason: 'User cancelled' };
        }
      }
      
      // 执行 DOM 操作
      await this.executeStep(step);
      
      // 等待页面响应(如果是 SPA)
      if (this.isSPA()) {
        await this.waitForNetworkIdle();
      }
    }
    
    return { success: true, stepsCompleted: plan.steps.length };
  }
  
  private buildPrompt(instruction: string, dom: DehydratedElement[]): string {
    return `
当前页面结构(已脱水):
${dom.map(el => `[${el.id}] ${el.role}: "${el.text}" ${el.action === 'click' ? '(可点击)' : el.action === 'type' ? '(可输入)' : ''}`).join('\n')}

用户指令:${instruction}

请选择最合适的元素和操作。
输出格式:
{
  "reasoning": "解释你的思考过程",
  "steps": [
    { "elementId": "el-3", "action": "click", "reason": "点击登录按钮" }
  ]
}
`;
  }
}

四、安全模型:让 AI 在可控范围内操作

4.1 为什么安全特别重要

当 AI Agent 运行在你的网页里,它拥有相当大的能力——可以读取页面内容、填写表单、点击任意按钮。如果不加控制,后果可能是:

  • AI 读取用户密码/信用卡号并发送给第三方
  • AI 在用户不知情的情况下提交订单
  • AI 执行了未授权的管理员操作

Page Agent 提供了四层安全防护

4.2 操作白名单(Operation Allowlist)

const agent = new PageAgent({
  // 限制 AI 只能执行特定操作
  allowedActions: ['click', 'type', 'select', 'read'],
  // 禁止的操作列表
  deniedActions: ['submit-form', 'upload-file', 'navigate-external'],
  
  // 限制特定元素的操作
  elementRules: [
    {
      selector: '[type="password"]',
      allowedActions: ['read'],  // 只能读取,不能操作
      maskData: true             // 自动脱敏
    },
    {
      selector: '#checkout-form',
      requiresConfirmation: true  // 提交订单需要用户确认
    }
  ]
});

4.3 数据脱敏(Data Masking)

// 自动识别并脱敏敏感字段
agent.configureSecurity({
  // 识别模式(正则)
  sensitivePatterns: [
    { pattern: /credit.?card/i, type: 'CREDIT_CARD' },
    { pattern: /password/i, type: 'PASSWORD' },
    { pattern: /ssn|social.?security/i, type: 'SSN' },
    { pattern: /bank.?account/i, type: 'BANK_ACCOUNT' }
  ],
  
  // 脱敏策略
  maskingStrategy: {
    PASSWORD: '******',
    CREDIT_CARD: '****-****-****-1234',
    SSN: '***-**-****',
    BANK_ACCOUNT: '****末尾' + last4
  },
  
  // 替换规则:AI 看到的是脱敏后的数据
  // 但提交时用原始数据替换
});

4.4 知识规则引擎(Knowledge Rules)

// 业务规则配置:让 AI 理解业务逻辑而不需要访问后端
agent.configureKnowledge({
  // 业务规则:定义操作边界
  rules: [
    {
      condition: "action === 'submit-order' && amount > 10000",
      response: "请确认:大额订单(超过1万元)需要主管审批"
    },
    {
      condition: "user.role !== 'admin' && target === '/admin'",
      response: "您没有管理员权限,无法访问此页面"
    },
    {
      condition: "action === 'delete' && target.type === 'user'",
      response: "删除用户需要二次确认"
    }
  ],
  
  // 知识库:给 AI 提供业务背景知识
  knowledgeBase: [
    "我们的产品分为 Starter/Pro/Enterprise 三个版本",
    "企业版用户可以开通 SSO 单点登录",
    "表单中标记 * 的字段为必填项",
    "提交订单前需要选择配送地址"
  ]
});

4.5 Human-in-the-Loop 实时干预

// 操作面板允许用户随时干预
agent.panel.on('step-executing', (step) => {
  // 显示当前步骤给用户
  showNotification(`AI 正在执行: ${step.description}`);
});

agent.panel.on('step-complete', (step) => {
  showNotification(`✅ 完成: ${step.description}`);
});

agent.panel.on('error', (error) => {
  showError(`❌ 出错: ${error.message}`);
  // 用户可以点击"重试"或"跳过"
});

// 用户可以随时中止
agent.panel.on('abort-requested', () => {
  agent.abort();
  showNotification('⏹ 用户已中止');
});

五、MCP 集成:让 Page Agent 成为 AI Agent 的浏览器控制模块

5.1 MCP 是什么

Model Context Protocol (MCP) 是 Anthropic 提出的标准化协议,让 AI Agent 可以调用外部工具。Page Agent 提供了 MCP Server,可以让任何 MCP 客户端 Agent(如 Claude Desktop、Cursor Agent)使用浏览器作为工具。

// 启动 Page Agent MCP Server
import { createMcpServer } from 'page-agent/mcp';

const server = createMcpServer({
  port: 3000,
  // 可选:跨标签页协作
  enableCrossTab: true,
});

server.start();
// Claude Desktop 配置 (claude_desktop_config.json)
{
  "mcpServers": {
    "page-agent": {
      "command": "npx",
      "args": ["page-agent-mcp", "--port", "3000"]
    }
  }
}

5.2 MCP Server 提供的工具

// Page Agent MCP Server 暴露给 AI 的工具

// 工具 1:截图分析(作为 fallback)
{
  name: "page_agent_vision_snapshot",
  description: "Take a screenshot and analyze the page visually. Use as fallback when DOM analysis is insufficient.",
  inputSchema: {
    type: "object",
    properties: {
      focus_area: { 
        type: "string",
        description: "Specific area to focus on (optional)"
      }
    }
  }
}

// 工具 2:DOM 分析
{
  name: "page_agent_analyze_dom",
  description: "Get dehydrated DOM structure of the current page",
  inputSchema: {
    type: "object",
    properties: {
      max_elements: { type: "number", default: 200 }
    }
  }
}

// 工具 3:执行操作
{
  name: "page_agent_execute",
  description: "Execute a natural language instruction on the page",
  inputSchema: {
    type: "object",
    properties: {
      instruction: { type: "string" },
      max_steps: { type: "number", default: 10 }
    }
  }
}

// 工具 4:读取页面内容
{
  name: "page_agent_read",
  description: "Extract specific information from the page",
  inputSchema: {
    type: "object",
    properties: {
      selector: { type: "string" },
      query: { type: "string", description: "自然语言查询,如'找到所有价格信息'" }
    }
  }
}

// 工具 5:填写表单
{
  name: "page_agent_fill",
  description: "Fill form fields with structured data",
  inputSchema: {
    type: "object",
    properties: {
      fields: {
        type: "array",
        items: {
          type: "object",
          properties: {
            selector: { type: "string" },
            value: { type: "string" }
          }
        }
      }
    }
  }
}

5.3 跨页面 Agent 协作

Page Agent 还提供了可选的 Chrome 扩展,实现跨标签页任务:

// 启动跨页面协作
const agent = new PageAgent({
  enableCrossTab: true,
  chromeExtensionId: 'your-extension-id'
});

// 例子:跨页面填写订单
await agent.execute(`
  1. 在页面 A 找到商品价格
  2. 切换到页面 B 填写订单
  3. 在页面 C 确认支付
`);

六、生产级实战:三大核心场景

场景一:SaaS 产品 AI Copilot

痛点:复杂的 B2B SaaS 产品(如 ERP、CRM、数据分析平台),新用户上手困难,需要大量培训。

传统方案

  • 写详细的产品文档
  • 制作视频教程
  • 招聘客服团队
  • 开发功能引导(onboarding flow)

Page Agent 方案

// 在你的 SaaS 产品中嵌入 Page Agent
// React/Vue/Angular 均可使用

import { PageAgent } from 'page-agent';
import React, { useEffect } from 'react';

function SaaSCopilot() {
  const agentRef = useRef(null);
  
  useEffect(() => {
    agentRef.current = new PageAgent({
      model: 'qwen-max',
      apiKey: process.env.REACT_APP_LLM_KEY,
      language: getUserLanguage(),
    });
    
    // 自定义业务知识
    agentRef.current.configureKnowledge({
      rules: [
        {
          condition: "action === 'create-report'",
          response: "报表创建流程:请先选择数据源,然后配置字段映射"
        }
      ]
    });
    
    agentRef.current.panel.show();
  }, []);
  
  return null; // 面板会自动渲染
}

// 用户体验:
// 用户在输入框说:"帮我创建一个月度销售报表"
// AI 自动导航到"报表" → 点击"新建" → 选择"月度模板"
// → 配置筛选条件 → 生成并展示结果

效果对比

维度传统文档方案Page Agent 方案
用户完成任务时间10-15 分钟30 秒
需要学习的操作20+ 个点击1 句话
客服工单减少~15%~60%
开发成本高(引导流程)低(集成 SDK)

场景二:遗留系统(Legacy System)现代化

痛点:企业存在大量 10-20 年历史的内部系统(ERP、MES、SCM),界面老旧、流程复杂。但重写系统的成本极高(可能需要数年)。

实际案例:某制造企业的工时填报系统

  • 基于 ExtJS 框架(2008年技术)
  • 提交一个工时需要:导航→选择日期→选择项目→选择工序→输入工时→验证→提交(15次点击)
  • 员工怨声载道,管理层想重写,预算 500 万,工期 18 个月

Page Agent 方案

// 只需在前端页面引入 Page Agent
const agent = new PageAgent({
  model: 'qwen-plus',
  apiKey: 'internal-llm-proxy',  // 企业内网 LLM 代理
  language: 'zh-CN',
  
  // 适配遗留系统的配置
  compatibility: {
    legacySelectors: {
      // 遗留系统常用的复杂选择器映射
      '工时输入框': '#ext-gen-234 input',
      '提交按钮': '.x-btn-center >> text=提交',
      '日期控件': 'div[id^="datepicker"]'
    },
    waitForAjax: true,  // 等待 AJAX 请求完成
    waitForExtJS: true // 等待 ExtJS 渲染完成
  }
});

agent.configureKnowledge({
  rules: [
    {
      condition: "action === 'submit' && !validateHours()",
      response: "工时不能为空,且必须在 0.5-24 之间"
    },
    {
      condition: "action === 'submit' && !validateDate()",
      response: "不能填报未来日期的工时"
    }
  ],
  knowledgeBase: [
    "本系统用于填报生产工时",
    "工时单位为小时,最小填报 0.5 小时",
    "每个工作日的工时总和应为 8 小时(标准工时)",
    "加班工时需要主管审批"
  ]
});

// 用户体验:输入"填报昨天焊接工时 6 小时"

效果

  • 开发成本:500 万 → 10 万(只需要前端集成)
  • 工期:18 个月 → 1 周
  • 用户满意度:从 2.1/5 提升到 4.3/5

场景三:无障碍增强(Accessibility)

痛点:视觉障碍用户使用网页困难,传统的屏幕阅读器需要大量学习成本。

Page Agent 的无障碍方案

const agent = new PageAgent({
  // 专为无障碍设计的配置
  accessibility: {
    enableVoice: true,           // 支持语音输入
    enableScreenReader: true,    // 与 NVDA/JAWS 兼容
    highContrast: true,          // 高对比度模式
    
    // 语义增强:AI 帮助理解复杂页面结构
    semanticEnhancement: {
      // 识别页面中的数据关系
      dataRelationships: [
        { type: 'table', identify: 'pricing-table' },
        { type: 'form', identify: 'registration-form' },
        { type: 'navigation', identify: 'main-nav' }
      ],
      
      // 自动描述复杂组件
      componentDescriptions: {
        'calendar-widget': '日历选择器,可以选择日期范围',
        'multi-select': '多选下拉框,支持 Ctrl+点击多选',
        'drag-drop': '可拖拽区域,支持拖拽排序'
      }
    }
  }
});

// 使用示例:
// 盲人用户说:"提交昨天到今天的差旅报销"
// AI 理解意图 → 导航到差旅报销页面 → 填写日期范围
// → 填写金额 → 提交 → 朗读确认信息

七、与 Browser-use 的深度对比

Page Agent 站在 browser-use 的肩膀上,但两者有本质区别:

维度Page AgentBrowser-use
定位面向产品开发者:将 Agent 嵌入你的网站面向个人用户:自动化整个浏览器
运行位置页面内嵌 JavaScript独立 Python 应用
控制范围仅当前页面所有打开的标签页
API 调用成本文本交互(~500 tokens/次)图片交互(~2000+ tokens/次)
准确性DOM 精确匹配视觉近似匹配
部署难度一行代码需要 Python + 浏览器驱动
安全模型内置操作白名单、数据脱敏需要自己实现安全逻辑
目标用户产品经理、开发者自动化工程师、普通用户
许可证MITMIT
// 实际的选择决策树:

if (useCase === '我要给我的 Web 产品加 AI 能力') {
  // → Page Agent
} else if (useCase === '我要自动化访问某个网站(爬虫/表单)') {
  // → Browser-use / Playwright + AI
} else if (useCase === '我要做一个通用浏览器 Agent 助手') {
  // → OpenAI Operator / Claude Computer Use
}

八、性能优化与最佳实践

8.1 Token 消耗优化

// 默认脱水策略
const agent = new PageAgent({
  // 控制脱水深度
  dehydration: {
    maxElements: 200,           // 最多保留 200 个元素
    excludeSelectors: [         // 排除干扰元素
      '[class*="analytics"]',   // 统计脚本
      '[class*="tracking"]',    // 追踪代码
      '[class*="cookie"]',      // Cookie 提示
      '[class*="modal-backdrop"]', // 模态框遮罩
      '.advertisement',           // 广告
      '#sidebar-hidden-items',   // 隐藏侧边栏
    ],
    // 优先级保留
    prioritySelectors: [
      'nav a',                    // 导航链接优先
      'form input, form button', // 表单元素优先
      '[aria-label]',            // 有无障碍标签的优先
      '[role="button"]',         // 角色按钮优先
    ],
    // 文本截断
    maxTextLength: 100,          // 单个元素文本最多 100 字符
  }
});

8.2 大型表单优化

// 分步处理复杂表单
class SmartFormHandler {
  async fillLargeForm(
    formData: Record<string, string>,
    agent: PageAgent
  ) {
    // 分析表单结构
    const dom = await agent.analyze();
    const formSections = this.identifySections(dom);
    
    // 按区块分步填写
    for (const section of formSections) {
      const relevantData = this.filterDataForSection(formData, section);
      
      await agent.execute(
        `填写 ${section.name}:${JSON.stringify(relevantData)}`
      );
      
      // 等待验证通过
      await this.waitForValidation(section, agent);
    }
  }
}

8.3 SPA(单页应用)特殊处理

// Page Agent 对 React/Vue/Angular 等 SPA 的特殊支持
const agent = new PageAgent({
  spa: {
    // 监听路由变化
    watchHistoryApi: true,
    watchHashChange: true,
    
    // 等待应用状态稳定
    waitForConditions: [
      {
        check: () => !document.querySelector('.loading-spinner'),
        timeout: 5000
      },
      {
        check: () => document.readyState === 'complete',
        timeout: 3000
      },
      {
        // 等待特定数据加载(如用户信息)
        check: () => window.__APP_STATE__.user !== null,
        timeout: 10000
      }
    ],
    
    // 动态内容监控
    observeMutations: true,
    mutationDebounce: 500  // 防抖 500ms
  }
});

九、局限性与未来展望

9.1 当前局限性

① 复杂动态内容处理

// 挑战:Canvas 绑定的图表、富媒体播放器
// Page Agent 无法理解 <canvas> 绘制的图表内容
// 解决方案:提供结构化数据 API,让 AI 读取数据而非截图

② 跨 iframe 操作

// 挑战:iframe 内部的 DOM 受同源策略限制
// 解决:Page Agent 支持检测 iframe,但操作有限制
const result = agent.analyze({ includeIframes: true });
// iframe 内的内容会被标记为 "cross-origin, limited access"

③ 登录态管理

// 挑战:页面内 Agent 无法自动处理复杂登录流程
// 解决:建议开发者通过后端代理持有登录态
agent.configure({
  // 通过代理处理需要登录态的 API
  apiProxy: 'https://your-backend.com/api/proxy',
  // 页面操作仍然由 Page Agent 处理
});

9.2 未来发展方向

根据 GitHub Issues 和 Discussions 的讨论,Page Agent 团队计划:

  1. 更强大的视觉 fallback:当 DOM 分析不够时,无缝切换到视觉分析
  2. 多语言模型路由:根据任务类型自动选择最合适的模型
  3. 设备适配:从桌面浏览器扩展到移动端 WebView
  4. 协作功能:多用户同时使用同一个 Agent 面板
  5. 离线模式:支持本地运行的模型(如 Ollama)

十、总结:重新定义 Web 自动化的边界

Page Agent 带来的最深刻改变,不是技术层面的,而是思路层面的

从"让 AI 控制浏览器"到"让 AI 活在网页里"

这意味着:

  • AI Agent 不再是一个外部工具,而是你产品的一部分
  • 用户不需要切换到另一个界面来使用 AI——AI 就在他们正在使用的页面中
  • 开发者不需要构建复杂的自动化基础设施——只需要几行代码

对于程序员茄子的读者来说,这个项目的启示在于:有时候最好的解决方案不是最强大的那个,而是最合适的那一个。Page Agent 没有追求 GPT-5 级别的通用能力,而是专注于"让网页开口说话"这一个场景,做到了极致的集成体验。

在 2026 年 AI Agent 军备竞赛中,这种"聚焦场景、打磨体验"的工程思路,或许比一味追求"更大更强"的模型更有参考价值。


相关资源

  • GitHub:https://github.com/alibaba/page-agent
  • 官方文档:https://alibaba.github.io/page-agent/
  • 在线 Demo:https://alibaba.github.io/page-agent/
  • MCP Server:https://alibaba.github.io/page-agent/docs/features/mcp-server
  • Chrome 扩展:https://alibaba.github.io/page-agent/docs/features/chrome-extension

推荐文章

实现微信回调多域名的方法
2024-11-18 09:45:18 +0800 CST
html流光登陆页面
2024-11-18 15:36:18 +0800 CST
一个简单的打字机效果的实现
2024-11-19 04:47:27 +0800 CST
PHP如何进行MySQL数据备份?
2024-11-18 20:40:25 +0800 CST
使用Python提取图片中的GPS信息
2024-11-18 13:46:22 +0800 CST
程序员茄子在线接单