# https://github.com/tinyfish-io/agentql 项目说明书

生成时间：2026-05-30 22:37:25 UTC

## 目录

- [AgentQL 项目介绍](#project-introduction)
- [快速入门指南](#quick-start)
- [Python SDK 详解](#python-sdk)
- [JavaScript SDK 详解](#javascript-sdk)
- [浏览器调试器扩展](#debugger-extension)
- [Python 示例代码集](#python-examples)
- [JavaScript 示例代码集](#javascript-examples)
- [高级使用模式](#advanced-patterns)
- [第三方集成](#integrations)
- [Cloudflare 浏览器渲染集成](#cloudflare-integration)

<a id='project-introduction'></a>

## AgentQL 项目介绍

### 相关页面

相关主题：[快速入门指南](#quick-start), [Python SDK 详解](#python-sdk), [JavaScript SDK 详解](#javascript-sdk)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)
- [examples/examples.md](https://github.com/tinyfish-io/agentql/blob/main/examples/examples.md)
- [examples/python/first_steps/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)
- [examples/python/list_query_usage/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/README.md)
- [examples/js/collect-paginated-news-headlines/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-paginated-news-headlines/README.md)
- [examples/js/submit-form/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/submit-form/README.md)
- [examples/python/perform_sentiment_analysis/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/perform_sentiment_analysis/README.md)
</details>

# AgentQL 项目介绍

AgentQL 是一个将大语言模型（LLM）和 AI Agent 连接到整个 Web 的开源项目。通过自然语言查询和结构化数据提取能力，AgentQL 让开发者能够以声明式的方式与网页交互，无需依赖脆弱的 CSS 选择器或 XPath 表达式。资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

## 项目概述

AgentQL 由 [tinyfish-io](https://github.com/tinyfish-io) 团队开发，旨在解决传统网页自动化和爬虫技术中的核心痛点：UI 变化导致的脚本失效问题。传统的网页抓取方案通常依赖固定的 DOM 选择器，一旦网站更新界面结构，爬虫脚本就会中断。AgentQL 采用自然语言理解的方式定位页面元素，即使网页布局发生变化，只要语义内容保持一致，查询仍然有效。资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

该项目的设计理念是让 AI 代理能够像人类用户一样理解和使用网页，通过智能定位器（Smart Locator）和数据查询 API 实现网页元素的自动发现与数据提取。资料来源：[examples/python/first_steps/main.py:1-20](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

## 核心功能特性

### 自然语言选择器

AgentQL 的核心优势在于使用自然语言描述来定位页面元素。开发者无需编写复杂的 CSS 选择器或 XPath，只需用人类可读的查询语句描述所需元素，系统即可自动识别匹配的 DOM 节点。资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

这种设计带来了三个显著优势：

- **跨站点兼容性**：相同的查询可以用于结构相似但具体实现不同的网站
- **UI 变化自愈能力**：页面结构改变时，只要语义内容保留，查询依然有效
- **降低学习成本**：非前端专业的开发者也能轻松编写网页交互脚本

### 结构化数据输出

AgentQL 支持在查询中定义期望的数据结构，系统会自动将提取的数据映射到预定义的格式中。通过查询语言可以指定字段类型转换，例如将价格字符串转换为整数。资料来源：[examples/python/first_steps/main.py:28-35](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

示例查询展示了如何提取产品列表数据：

```graphql
{
    price_currency
    products[] {
        name
        price(integer)
    }
}
```

此查询会返回包含货币类型、产品名称数组和整数类型价格的数据结构。资料来源：[examples/python/first_steps/main.py:28-35](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

### 转换与提取能力

除了基本的数据提取，AgentQL 还支持在查询过程中对数据进行即时转换处理。开发者可以在查询语句中指定数据类型转换规则，实现数据清洗和格式统一。资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

## SDK 工具矩阵

AgentQL 提供多语言 SDK 支持，涵盖主流开发环境：

| SDK 类型 | 安装文档 | 主要用途 |
|---------|---------|---------|
| Python SDK | [官方文档](https://docs.agentql.com/python-sdk/installation) | 自动化脚本、数据爬取 |
| JavaScript SDK | [官方文档](https://docs.agentql.com/javascript-sdk/installation) | Node.js 环境自动化 |
| REST API | [API 参考](https://docs.agentql.com/rest-api/api-reference) | 无 SDK 环境下的查询执行 |

资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

### Playwright 集成

AgentQL 与 Playwright 深度集成，为 Python 和 JavaScript 提供统一的操作接口。通过 `agentql.wrap()` 方法可以将 Playwright 的 Page 对象包装为支持自然语言查询的增强版本。资料来源：[examples/python/first_steps/main.py:50-52](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

```python
page = agentql.wrap(browser.new_page())
```

集成架构允许开发者同时使用 Playwright 的底层控制能力和 AgentQL 的智能查询功能。资料来源：[examples/python/first_steps/main.py:1-15](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

### API 方法体系

AgentQL 提供两类核心查询方法：

| 方法名 | 功能描述 | 返回类型 |
|-------|---------|---------|
| `query_elements()` | 查询页面 DOM 元素 | 元素定位器 |
| `query_data()` | 提取结构化数据 | 字典/对象 |
| `get_by_prompt()` | 通过自然语言提示定位元素 | 元素定位器 |

资料来源：[examples/python/first_steps/main.py:56-70](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

## 使用模式与示例

### 列表数据查询

列表查询是 AgentQL 最常见的应用场景之一，适用于商品列表、搜索结果、表格数据等需要批量提取的场景。资料来源：[examples/python/list_query_usage/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/README.md)

该模式的工作流程如下：

1. 定义查询语句，指定列表字段结构
2. 调用 `query_data()` 方法执行查询
3. 处理返回的结构化数组数据

### 分页数据采集

AgentQL 支持跨页数据采集场景。典型实现包括导航到分页页面、执行查询、点击下一页、重复采集的循环逻辑。资料来源：[examples/js/collect-paginated-news-headlines/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-paginated-news-headlines/README.md)

```javascript
// JavaScript 分页采集示例结构
const headlines = [];
for (let page = 0; page < totalPages; page++) {
    const data = await page.queryData(NEWS_QUERY);
    headlines.push(...data.headlines);
    await page.click('.next-button');
}
```

### 表单自动填写

通过 AgentQL 的元素定位能力，可以自动化完成表单填写和提交操作。查询语句精确定位各个输入框和按钮，Playwright API 执行实际的交互动作。资料来源：[examples/js/submit-form/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/submit-form/README.md)

此模式常用于：

- 用户注册自动化
- 登录流程处理
- 在线调查问卷填写
- 多步骤向导表单

### 情感分析集成

AgentQL 可与外部 AI 模型集成，实现更高级的数据处理能力。典型架构是将 AgentQL 用于评论数据提取，随后将结果发送给 OpenAI 等大语言模型进行情感分析。资料来源：[examples/python/perform_sentiment_analysis/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/perform_sentiment_analysis/README.md)

```python
# 数据提取 + 情感分析流程
comments = page.query_data(COMMENTS_QUERY)
sentiment = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": f"Analyze: {comments}"}]
)
```

## 系统架构

AgentQL 的整体架构可分为四个层次：

```mermaid
graph TD
    A[用户查询层] --> B[AgentQL 查询引擎]
    B --> C[智能定位器]
    C --> D[Playwright 浏览器控制]
    B --> E[数据提取器]
    E --> F[结构化输出]
    
    G[LLM 集成层] --> B
    H[REST API 层] --> B
```

| 架构层次 | 组件 | 职责 |
|--------|------|------|
| 用户层 | SDK / REST API | 提供查询入口和配置接口 |
| 查询引擎 | Parser / Resolver | 解析查询语句，路由到对应处理器 |
| 定位层 | Smart Locator | 自然语言到 DOM 元素的映射 |
| 执行层 | Playwright Bridge | 浏览器实例管理和 DOM 操作 |

## 典型应用场景

### 电商数据采集

AgentQL 可用于从电商网站提取商品信息、价格、库存状态等数据。由于其跨站点兼容性，同一套查询语句经过适当调整后可应用于多个电商平台。资料来源：[examples/python/first_steps/main.py:1-100](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

### 社交媒体监控

结合分页采集功能，AgentQL 能够监控社交媒体平台上的帖子、评论和用户互动数据。与情感分析模型结合，可构建舆情监控系统。资料来源：[examples/js/collect-youtube-comments/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-youtube-comments/README.md)

### AI Agent 网页交互

AgentQL 的设计初衷是让 AI Agent 能够自主操作网页。通过自然语言指令，Agent 可以搜索信息、填写表单、点击按钮，执行复杂的网页任务序列。资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

## 框架集成

AgentQL 提供与主流 Agent 框架和自动化工具的集成能力：

| 集成类型 | 框架/工具 | 集成方式 |
|---------|----------|---------|
| Agent 框架 | Langchain | Python SDK 集成 |
| 自动化平台 | Zapier | API 集成 |
| AI 代理协议 | MCP Server | Model Context Protocol |
| 边缘计算 | Cloudflare Workers | Playwright 集成 |

资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

### Cloudflare Workers 环境

社区反馈表明，有用户尝试在 Cloudflare 的 Browser Rendering 环境中使用 AgentQL JavaScript SDK。该环境基于 Playwright 构建，但由于边缘计算的特殊限制，可能需要额外的适配工作。资料来源：[AgentQL (JS) x Cloudflare's Browser Rendering #128](https://github.com/tinyfish-io/agentql/issues/128)

## 社区与资源

### 示例代码库

项目中包含了丰富的示例代码，涵盖 Python 和 JavaScript 两大生态：

| 示例类型 | Python 路径 | JavaScript 路径 |
|---------|------------|----------------|
| 基础教程 | examples/python/first_steps | - |
| 列表查询 | examples/python/list_query_usage | examples/js/list-query-usage |
| 分页采集 | examples/python/collect_paginated_news_headlines | examples/js/collect-paginated-news-headlines |
| 表单提交 | - | examples/js/submit-form |
| 情感分析 | examples/python/perform_sentiment_analysis | examples/js/perform-sentiment-analysis |
| 页面等待 | examples/python/wait_for_entire_page_load | examples/js/wait-for-entire-page-load |

资料来源：[examples/examples.md](https://github.com/tinyfish-io/agentql/blob/main/examples/examples.md)

### 调试工具

官方提供了 [AgentQL Debugger Chrome 扩展程序](https://docs.agentql.com/installation/chrome-extension-installation)，允许开发者在浏览器中实时测试和调试查询语句。该工具对于理解查询匹配逻辑和优化查询性能非常有帮助。资料来源：[examples/python/list_query_usage/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/README.md)

### 文档资源

| 资源类型 | 链接 |
|---------|------|
| 官方文档 | https://docs.agentql.com |
| 快速开始 | https://docs.agentql.com/quick-start |
| 查询语言指南 | https://docs.agentql.com/agentql-query/query-intro |
| Discord 社区 | https://discord.gg/agentql |
| Twitter | https://twitter.com/agentql |

## 技术优势分析

与传统网页抓取方案相比，AgentQL 具有以下技术优势：

| 对比维度 | 传统方案 | AgentQL |
|---------|---------|---------|
| 元素定位 | CSS/XPath 选择器 | 自然语言描述 |
| 抗 UI 变化能力 | 脆弱，UI 变化即失效 | 鲁棒，语义匹配自愈 |
| 跨站点复用 | 需为每个站点编写独立逻辑 | 查询可跨相似站点复用 |
| 数据提取 | 手动解析 DOM 结构 | 查询中定义结构自动映射 |
| AI 集成 | 需额外开发 | 原生支持 LLM 集成 |

## 已知限制与注意事项

### 元素定位精度

社区反馈表明，在某些复杂页面结构中，查询可能返回语义相近但非目标的元素。例如，页面中包含多个视觉相似的 `<span>` 元素时，查询可能解析到错误的目标。资料来源：[querying element resolved as useless span #121](https://github.com/tinyfish-io/agentql/issues/121)

建议在使用 `get_by_prompt()` 方法后验证返回元素是否正确：

```python
element = page.get_by_prompt("提交按钮")
if element:
    element.click()
```

### 边缘环境限制

JavaScript SDK 在 Cloudflare Workers 等边缘计算环境中使用时，由于 Node.js API 的部分限制，可能需要额外的配置或替代方案。资料来源：[AgentQL (JS) x Cloudflare's Browser Rendering #128](https://github.com/tinyfish-io/agentql/issues/128)

## 快速开始指南

### 安装步骤

**Python SDK 安装：**

```bash
pip install agentql
```

**JavaScript SDK 安装：**

```bash
npm install agentql
```

### 基础使用流程

1. **导入并初始化**：使用 `agentql.wrap()` 包装 Playwright Page 对象
2. **编写查询语句**：使用 GraphQL 风格的查询定义目标和数据结构
3. **执行查询**：调用 `query_elements()`、`query_data()` 或 `get_by_prompt()`
4. **交互操作**：使用返回的定位器执行点击、输入等操作
5. **数据处理**：解析返回的结构化数据

资料来源：[examples/python/first_steps/main.py:50-85](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

## 发展趋势

AgentQL 正在扩展其生态系统的覆盖范围，包括与更多 AI Agent 框架的深度集成、MCP（Model Context Protocol）服务器的完善，以及针对企业级用例的功能增强。资料来源：[Monetize AgentQL with run.pay #153](https://github.com/tinyfish-io/agentql/issues/153)

项目团队也在积极听取社区反馈，持续优化查询解析算法以提高定位精度，并为复杂应用场景提供更多最佳实践指南。

---

<a id='quick-start'></a>

## 快速入门指南

### 相关页面

相关主题：[AgentQL 项目介绍](#project-introduction), [Python SDK 详解](#python-sdk), [JavaScript 示例代码集](#javascript-examples)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/python/first_steps/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)
- [examples/js/first-steps/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/first-steps/main.js)
- [examples/python/run_script_online_in_google_colab/main.ipynb](https://github.com/tinyfish-io/agentql/blob/main/examples/python/run_script_online_in_google_colab/main.ipynb)
- [examples/python/news-aggregator/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)
- [examples/python/news-aggregator/main_sync.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main_sync.py)
- [examples/js/package.json](https://github.com/tinyfish-io/agentql/blob/main/examples/js/package.json)
</details>

# 快速入门指南

## 概述

AgentQL 是一个用于从网页中提取数据和自动化网页交互的工具套件，通过自然语言查询语言连接 LLMs 和 AI Agents 与整个互联网。该项目提供 Python SDK 和 JavaScript SDK，可与 Playwright 无缝集成，支持跨网站兼容性、结构化输出、自然语言选择器以及 UI 变化自愈能力。

本文档将帮助用户在 5 分钟内快速上手 AgentQL，完成从安装到运行第一个脚本的全流程。

---

## 环境要求

| 组件 | 要求 |
|------|------|
| Python 版本 | Python 3.8+（推荐 3.13） |
| Node.js 版本 | Node.js 16+ |
| Playwright | 浏览器自动化框架（自动安装） |
| 网络 | 互联网连接（用于访问 AgentQL API） |

---

## 安装指南

### Python SDK 安装

通过 pip 安装 AgentQL Python SDK：

```bash
pip install agentql
```

安装完成后，还需安装 Playwright 浏览器驱动：

```bash
playwright install chromium
```

资料来源：[examples/python/news-aggregator/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)

### JavaScript SDK 安装

在 Node.js 项目中安装依赖：

```bash
npm install agentql playwright
```

JavaScript SDK 的 package.json 配置示例：

```json
{
  "dependencies": {
    "agentql": "latest",
    "playwright": "^1.48.2",
    "playwright-dompath": "^0.0.7"
  }
}
```

资料来源：[examples/js/package.json](https://github.com/tinyfish-io/agentql/blob/main/examples/js/package.json)

---

## Python 快速开始

### 基本用法

以下示例展示如何使用 Python SDK 查询网页数据：

```python
import asyncio
from playwright.async_api import async_playwright
import agentql

QUERY = """
{
    items {
        entry
        url
        outlet
        author
    }
}
"""

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        page = await agentql.wrap_async(context.new_page())
        
        await page.goto("https://news.google.com")
        data = await page.query_data(QUERY)
        
        print(data)
        await browser.close()

asyncio.run(main())
```

资料来源：[examples/python/first_steps/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

### 同步版本

如果不需要异步操作，可以使用同步 API：

```python
from playwright.sync_api import sync_playwright
import agentql

def main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context()
        page = agentql.wrap(context.new_page())
        
        page.goto("https://news.google.com")
        data = page.query_data(QUERY)
        
        print(data)
        browser.close()
```

资料来源：[examples/python/news-aggregator/main_sync.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main_sync.py)

### 工作流程图

```mermaid
graph TD
    A[安装 agentql 和 playwright] --> B[启动浏览器]
    B --> C[创建 BrowserContext]
    C --> D[包装 Page 对象]
    D --> E[访问目标 URL]
    E --> F[执行 AgentQL 查询]
    F --> G[获取结构化数据]
    G --> H[关闭浏览器]
```

---

## JavaScript 快速开始

### 基本用法

以下示例展示如何使用 JavaScript SDK：

```javascript
const { chromium } = require('playwright');
const agentql = require('agentql');

const QUERY = `
{
    items {
        entry
        url
        outlet
        author
    }
}
`;

async function main() {
    const playwright = await chromium.launch({ headless: true });
    const context = await playwright.newContext();
    const page = await agentql.wrapAsync(context.newPage());
    
    await page.goto('https://news.google.com');
    const data = await page.queryData(QUERY);
    
    console.log(data);
    await playwright.close();
}

main();
```

资料来源：[examples/js/first-steps/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/first-steps/main.js)

---

## Google Colab 集成

AgentQL 支持在 Google Colab 中运行，无需本地环境配置：

1. 访问 [Google Colab 示例笔记本](https://github.com/tinyfish-io/agentql/blob/main/examples/python/run_script_online_in_google_colab/main.ipynb)

2. 在 Colab 中直接运行代码单元

3. 示例查询语法与本地 Python SDK 完全一致

```python
!pip install agentql playwright
!playwright install chromium

import agentql
from playwright.async_api import async_playwright

# 运行查询代码
```

资料来源：[examples/python/run_script_online_in_google_colab/main.ipynb](https://github.com/tinyfish-io/agentql/blob/main/examples/python/run_script_online_in_google_colab/main.ipynb)

---

## AgentQL 查询语言基础

### 查询结构

AgentQL 使用自然语言风格的查询语法来定义要提取的数据结构：

```graphql
{
    items {
        entry
        url
        outlet
        author
    }
}
```

### 常见查询模式

| 模式 | 描述 | 示例 |
|------|------|------|
| 列表查询 | 提取重复元素列表 | `items { title, link }` |
| 嵌套查询 | 提取嵌套结构数据 | `product { name, price, reviews }` |
| 变换提取 | 在查询中转换数据 | 支持数据清洗和格式化 |

---

## 高级用法

### 分页数据收集

处理分页网站时，需要循环翻页并收集数据：

```python
import asyncio
from playwright.async_api import async_playwright
import agentql

QUERY = """
{
    headlines {
        text
        link
    }
    next_button @continue_if_exists
}
"""

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        page = await agentql.wrap_async(context.new_page())
        
        all_headlines = []
        
        for page_num in range(3):  # 收集 3 页数据
            await page.goto(f"https://news.ycombinator.com/?p={page_num + 1}")
            data = await page.query_data(QUERY)
            all_headlines.extend(data.get("headlines", []))
            
            # 点击下一页
            if data.get("next_button"):
                await page.click(data["next_button"])
        
        print(f"Total headlines collected: {len(all_headlines)}")
        await browser.close()

asyncio.run(main())
```

### 并发数据采集

使用 `asyncio.gather` 在同一浏览器上下文中并发打开多个标签页：

```python
async def main():
    WEBSITE_URLS = [
        "https://news.google.com/?q=AI",
        "https://news.ycombinator.com/",
    ]
    
    async with async_playwright() as p, await p.chromium.launch(headless=True) as browser:
        context = await browser.new_context()
        
        # 并发获取多个 URL 的数据
        await asyncio.gather(
            *(fetch_data(context, url) for url in WEBSITE_URLS)
        )
```

资料来源：[examples/python/news-aggregator/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)

---

## 数据导出

### 保存为 CSV

```python
import os

CSV_FILE_PATH = "news_headlines.csv"

def save_to_csv(data):
    if not os.path.exists(CSV_FILE_PATH):
        with open(CSV_FILE_PATH, "w", encoding="utf-8") as file:
            file.write("Posted | Entry | URL | Platform | Author\n")
            file.writelines(data)
    else:
        with open(CSV_FILE_PATH, "a", encoding="utf-8") as file:
            file.writelines(data)
```

---

## 常见问题与解决方案

### 1. 查询结果为空或定位不准确

如果查询返回无用元素（如 `span` 而非预期元素），可以：
- 使用 AgentQL Debugger Chrome 扩展调试查询
- 调整查询语句，使用更具体的描述

社区讨论参考：[Issue #121 - querying element resolved as useless span](https://github.com/tinyfish-io/agentql/issues/121)

### 2. Cloudflare Workers 环境限制

在 Cloudflare Workers 边缘环境中运行需要注意：
- 部分 Node.js API 在边缘环境中不可用
- 需要使用 Browser Rendering 功能的兼容配置

社区讨论参考：[Issue #128 - AgentQL (JS) x Cloudflare's Browser Rendering](https://github.com/tinyfish-io/agentql/issues/128)

### 3. 文档链接问题

如遇文档链接失效，请参考：
- 正确路径：`examples/run_script_online_in_google_colab`
- 文档页：`https://docs.agentql.com/examples`

社区讨论参考：[Issue #64 - Invalid Link | Documentation > Examples > Collab](https://github.com/tinyfish-io/agentql/issues/64)

---

## 下一步

| 资源 | 链接 |
|------|------|
| 官方文档 | [docs.agentql.com](https://docs.agentql.com) |
| 查询语言参考 | [AgentQL Query Language](https://docs.agentql.com/agentql-query/query-intro) |
| Chrome 扩展 | [AgentQL Debugger](https://docs.agentql.com/installation/chrome-extension-installation) |
| Discord 社区 | [Join Discord](https://discord.gg/agentql) |
| 更多示例 | [examples 目录](https://github.com/tinyfish-io/agentql/tree/main/examples) |

---

<a id='python-sdk'></a>

## Python SDK 详解

### 相关页面

相关主题：[JavaScript SDK 详解](#javascript-sdk), [浏览器调试器扩展](#debugger-extension), [Python 示例代码集](#python-examples)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/python/first_steps/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)
- [examples/python/collect_ecommerce_pricing_data/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/collect_ecommerce_pricing_data/main.py)
- [examples/python/list_query_usage/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/main.py)
- [examples/python/news-aggregator/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)
- [examples/python/maps_scraper/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/maps_scraper/main.py)
- [examples/python/compare_product_prices/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/compare_product_prices/main.py)
</details>

# Python SDK 详解

## 概述

AgentQL Python SDK 是连接 LLM 和 AI Agent 与网页的核心工具库。该 SDK 通过扩展 Playwright 的 Page 对象，提供了一套声明式的查询语言和 API，使开发者能够以自然、灵活的方式从网页中提取数据并与之交互。

Python SDK 的核心价值在于：

- **自然语言选择器**：使用类似 GraphQL 的查询语言定位页面元素
- **结构化输出**：查询结果直接映射为 Python 字典数据结构
- **跨站点兼容**：同一查询可适用于具有相似结构的多个网站
- **UI 变化适应性**：查询具有自愈能力，能应对页面结构的微小变化

资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

## 核心概念与架构

### SDK 在整体架构中的位置

```mermaid
graph TD
    A[开发者代码] --> B[AgentQL Python SDK]
    B --> C[Playwright API]
    C --> D[浏览器实例]
    D --> E[目标网页]
    
    F[AgentQL 查询语言] --> B
    G[自然语言提示] --> B
```

AgentQL Python SDK 建立在 Playwright 之上，通过 `wrap()` 方法将标准的 Playwright Page 对象转换为增强版对象，从而获得 AgentQL 特有的查询能力。

资料来源：[examples/python/first_steps/main.py:16-17](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py#L16-L17)

## 安装与基础配置

### 环境要求

| 组件 | 要求 |
|------|------|
| Python | 3.8+ |
| Playwright | 1.40+ |
| 操作系统 | Windows/macOS/Linux |

### 安装步骤

```bash
pip install agentql
playwright install chromium
```

### 基础导入

```python
import agentql
from agentql.ext.playwright.sync_api import Page
from playwright.sync_api import sync_playwright
```

资料来源：[examples/python/first_steps/main.py:1-10](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py#L1-L10)

## 核心 API

### 1. 包装 Page 对象

使用 `agentql.wrap()` 将 Playwright Page 对象转换为支持 AgentQL API 的对象：

```python
page = agentql.wrap(browser.new_page())
```

这是使用所有 AgentQL 特性的前提条件。包装后的 page 对象保留了 Playwright 的所有原生方法，同时新增了 AgentQL 特有的查询方法。

资料来源：[examples/python/first_steps/main.py:33-34](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py#L33-L34)

### 2. 查询数据 (query_data)

`query_data()` 方法是 SDK 最核心的功能，用于从页面中提取结构化数据：

```python
data = page.query_data(PRODUCT_DATA_QUERY)
```

**查询语法示例**：

```graphql
{
    price_currency
    products[] {
        name
        price(integer)
    }
}
```

查询结果直接返回 Python 字典：

```python
{
    'price_currency': '$',
    'products': [
        {'name': 'Bulbasaur', 'price': 5},
        {'name': 'Charmander', 'price': 6}
    ]
}
```

**特点说明**：

- 使用 `[]` 语法表示数组/列表
- 可以指定数据类型转换如 `(integer)`
- 支持嵌套对象结构

资料来源：[examples/python/first_steps/main.py:25-35](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py#L25-L35)

### 3. 查询元素 (query_elements)

`query_elements()` 用于定位 DOM 元素，返回元素对象后可使用 Playwright API 进行交互：

```python
response = page.query_elements(SEARCH_BOX_QUERY)
response.search_product_box.type(search_key_word, delay=200)
```

此方法返回的是一个包含查询字段的响应对象，每个字段对应一个可交互的 Playwright 元素。

资料来源：[examples/python/first_steps/main.py:63-67](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py#L63-L67)

### 4. 自然语言提示定位 (get_by_prompt)

`get_by_prompt()` 是 AgentQL 的独特功能，允许使用自然语言描述来定位元素：

```python
qwilfish_page_btn = page.get_by_prompt("Button to display Qwilfish page")
qwilfish_page_btn.click()
```

这种方法特别适合定位难以用传统选择器描述的按钮或链接。底层由 LLM 驱动，能够理解语义化的描述。

资料来源：[examples/python/first_steps/main.py:79-83](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py#L79-L83)

## 同步与异步 API

### 同步版本

适用于简单的脚本和批量处理场景：

```python
from playwright.sync_api import sync_playwright

with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=True)
    page = agentql.wrap(browser.new_page())
    page.goto(URL)
    data = page.query_data(QUERY)
```

资料来源：[examples/python/list_query_usage/main.py:1-19](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/main.py#L1-L19)

### 异步版本

适用于高性能并发场景：

```python
from playwright.async_api import async_playwright

async with async_playwright() as p:
    browser = await p.chromium.launch(headless=True)
    page = await agentql.wrap_async(browser.new_page())
    await page.goto(URL)
    data = await page.query_data(QUERY)
```

异步 API 使用 `agentql.wrap_async()` 进行包装，并通过 `await` 处理所有操作。

资料来源：[examples/python/news-aggregator/main.py:1-35](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py#L1-L35)

### 并发执行模式

异步版本支持高效的多标签页并发抓取：

```python
async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        await asyncio.gather(
            *(fetch_data(context, url) for url in WEBSITE_URLS)
        )

async def fetch_data(context, session_url):
    page = await agentql.wrap_async(context.new_page())
    await page.goto(session_url)
    data = await page.query_data(QUERY)
```

资料来源：[examples/python/news-aggregator/main.py:19-37](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py#L19-L37)

## 常见使用场景

### 场景一：电商数据采集

从电商网站提取产品列表和价格信息：

```python
URL = "https://scrapeme.live/shop"

QUERY = """
{
    products[] {
        name
        price(integer)
    }
}
"""

page.goto(URL)
response = page.query_data(QUERY)

with open("product_data.csv", "w") as f:
    f.write("Name, Price\n")
    for product in response["products"]:
        f.write(f"{product['name']},{product['price']}\n")
```

资料来源：[examples/python/list_query_usage/main.py:1-33](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/main.py#L1-L33)

### 场景二：价格比较

从不同电商平台获取同一商品的价格进行比较：

```python
PRODUCT_INFO_QUERY = """
{
    nintendo_switch_price
}
"""

page.goto(NINTENDO_URL)
nintendo_price = page.query_data(PRODUCT_INFO_QUERY)
print("Price at Nintendo:", nintendo_price["nintendo_switch_price"])

page.goto(TARGET_URL)
target_price = page.query_data(PRODUCT_INFO_QUERY)
print("Price at Target:", target_price["nintendo_switch_price"])
```

资料来源：[examples/python/compare_product_prices/main.py:1-45](https://github.com/tinyfish-io/agentql/blob/main/examples/python/compare_product_prices/main.py#L1-L45)

### 场景三：本地商家信息采集

```python
QUERY = """
{
    listings[] {
        name
        rating
        description
        order_link
        take_out_link
        address
        hours
    }
}
"""

page.goto(URL)
response = page.query_data(QUERY)

with open("map_data.csv", "w") as f:
    f.write("Name, Rating, Description, Order Link, Take Out Link, Address, Hours\n")
    for listing in response["listings"]:
        f.write(f"{listing['name']},{listing['rating']},...")
```

资料来源：[examples/python/maps_scraper/main.py:1-45](https://github.com/tinyfish-io/agentql/blob/main/examples/python/maps_scraper/main.py#L1-L45)

### 场景四：分页数据采集

```python
QUERY = """
{
    items[] {
        published_date
        entry
        author
        outlet
        url
    }
}
"""

for page_num in range(num_pages):
    page.goto(f"{BASE_URL}?page={page_num}")
    data = page.query_data(QUERY)
    all_items.extend(data["items"])
```

资料来源：[examples/python/news-aggregator/main.py:10-25](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py#L10-L25)

## 查询语言详解

### AgentQL 查询语法特点

| 语法 | 含义 | 示例 |
|------|------|------|
| `field` | 获取字段值 | `name` |
| `field[]` | 获取字段数组 | `products[]` |
| `field(type)` | 类型转换 | `price(integer)` |
| `(hint)` | 语义提示 | `Button to add` |

### 类型转换

支持的类型转换包括：

- `integer`：转换为整数
- `float`：转换为浮点数
- `string`：确保为字符串

### 语义提示

通过括号内的提示文本帮助 LLM 理解查询意图：

```graphql
{
    search_product_box
    published_date(convert to XX/XX/XXXX format)
}
```

资料来源：[examples/python/news-aggregator/main.py:10-25](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py#L10-L25)

## 已知限制与常见问题

### 元素定位不准确

社区反馈中提到了元素被解析为无用的 span 而非预期元素的问题：

> Issue #121: 使用 AgentQL 查询时，元素被解析为无用的 span 而非预期的目标元素

这通常发生在页面结构复杂或元素语义不明确时。解决方案包括：

1. 使用更具体的自然语言提示
2. 结合 Playwright 原生选择器进行二次筛选
3. 使用 `query_elements()` 获取元素后再通过 Playwright API 精确定位

### Cloudflare 边缘环境兼容

Issue #128 报告了在 Cloudflare Workers 边缘环境中使用 SDK 时遇到的问题：

> Cloudflare 的 Browser Rendering 支持 Playwright，但在边缘环境中存在某些 Node.js API 兼容性问题

对于边缘计算场景，建议使用标准环境部署。

## 数据模型

### 常见响应结构

```python
# 单对象查询
{
    "field1": "value1",
    "field2": "value2"
}

# 列表查询
{
    "items": [
        {"name": "Item 1", "price": 100},
        {"name": "Item 2", "price": 200}
    ]
}
```

### 文件输出模型

常见的数据持久化模式：

```python
CSV_FILE_PATH = "output.csv"

with open(CSV_FILE_PATH, "w", encoding="utf-8") as file:
    file.write("Header1, Header2, Header3\n")
    for item in data["items"]:
        file.write(f"{item['field1']},{item['field2']},{item['field3']}\n")
```

资料来源：[examples/python/news-aggregator/main_sync.py:45-58](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main_sync.py#L45-L58)

## 最佳实践

### 1. 选择合适的 API 版本

| 场景 | 推荐 API |
|------|----------|
| 简单脚本 | 同步 API |
| 批量处理 | 同步 API |
| 并发抓取 | 异步 API |
| 实时交互 | 异步 API |

### 2. 错误处理

```python
try:
    page.goto(URL, timeout=30000)
    data = page.query_data(QUERY)
except Exception as e:
    log.error(f"Failed to fetch data: {e}")
    return None
```

### 3. 性能优化

- 使用浏览器上下文复用减少启动开销
- 并发执行多个页面操作
- 设置合理的超时时间

### 4. 查询优化

- 使用具体的字段名称而非通配符
- 避免过度嵌套的查询结构
- 利用类型转换减少后处理需求

## 总结

AgentQL Python SDK 通过简洁直观的 API 设计，将复杂的网页交互和数据提取任务简化为声明式的查询操作。无论是简单的单页采集还是复杂的多源数据聚合，开发者都能利用这套工具高效完成任务。SDK 与 Playwright 的深度整合确保了良好的浏览器控制能力，而 AgentQL 查询语言则为跨站点兼容性和 UI 变化适应性提供了技术保障。

---

<a id='javascript-sdk'></a>

## JavaScript SDK 详解

### 相关页面

相关主题：[Python SDK 详解](#python-sdk), [JavaScript 示例代码集](#javascript-examples), [Cloudflare 浏览器渲染集成](#cloudflare-integration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/js/package.json](https://github.com/tinyfish-io/agentql/blob/main/examples/js/package.json)
- [examples/js/get-by-prompt/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/get-by-prompt/main.js)
- [examples/js/news-aggregator/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/news-aggregator/main.js)
- [examples/js/collect-pricing-data/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-pricing-data/main.js)
- [examples/js/collect-paginated-ecommerce-data/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-paginated-ecommerce-data/main.js)
- [examples/js/collect-paginated-news-headlines/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-paginated-news-headlines/README.md)
</details>

# JavaScript SDK 详解

## 概述

JavaScript SDK 是 AgentQL 为 Node.js 环境提供的官方开发工具包，使开发者能够在 JavaScript/TypeScript 项目中使用 AgentQL 的自然语言查询能力来自动化网页操作和数据提取。该 SDK 与 Playwright 无缝集成，继承了 Playwright 的全部浏览器控制功能，同时通过 AgentQL 查询语言增强了元素定位和数据提取的智能化程度。

## 核心功能

| 功能类别 | 说明 |
|---------|------|
| 页面包装 | 通过 `wrap()` 函数将 Playwright Page 对象转换为支持 AgentQL 查询的增强对象 |
| 配置管理 | 通过 `configure()` 设置 API 密钥等全局配置 |
| 数据查询 | 使用 `queryData()` 执行自然语言查询并获取结构化数据 |
| 元素定位 | 使用 `getByPrompt()` 通过自然语言描述定位页面元素 |
| 跨平台支持 | 支持 Chromium、Firefox、WebKit 等多浏览器引擎 |

## 安装与配置

### 环境要求

- Node.js 14.17.0 或更高版本
- npm、yarn 或 pnpm 包管理器

### 安装步骤

```bash
npm install agentql playwright
```

### 依赖配置

JavaScript SDK 的 package.json 中定义了核心依赖：

```json
{
  "dependencies": {
    "agentql": "latest",
    "openai": "^4.70.1",
    "playwright": "^1.48.2",
    "playwright-dompath": "^0.0.7"
  }
}
```

资料来源：[examples/js/package.json:13-17]()

### 全局配置

在使用 SDK 之前，需要通过 `configure()` 函数进行初始化：

```javascript
const { wrap, configure } = require('agentql');

// 配置 API 密钥
configure({
  apiKey: process.env.AGENTQL_API_KEY,
});
```

`configure()` 函数接受以下参数：

| 参数名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| apiKey | string | 否 | AgentQL API 密钥，默认从环境变量读取 |

## 核心 API

### wrap() 函数

`wrap()` 是 JavaScript SDK 的核心函数，用于将 Playwright 的 Page 对象转换为支持 AgentQL 查询的增强对象。

```javascript
const { wrap } = require('agentql');
const { chromium } = require('playwright');

const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();

// 将普通 Page 对象包装为 AgentQL Page 对象
const wrappedPage = await wrap(page);
```

资料来源：[examples/js/get-by-prompt/main.js:1-11]()

### queryData() 方法

`queryData()` 方法允许使用 AgentQL 查询语言从页面中提取结构化数据。

```javascript
const QUERY = `
{
    items[]
    {
        title
        url
        published_date(convert to XX/XX/XXXX format)
    }
}`;

const data = await wrappedPage.queryData(QUERY);
console.log(data.items);
```

资料来源：[examples/js/news-aggregator/main.js:1-18]()

### getByPrompt() 方法

`getByPrompt()` 通过自然语言描述定位页面元素，返回匹配的元素对象或 null。

```javascript
// 获取登录按钮
const signUpBtn = await wrappedPage.getByPrompt('Sign up button');

// 点击按钮
if (signUpBtn) {
    await signUpBtn.click();
}
```

资料来源：[examples/js/get-by-prompt/main.js:21-27]()

## 使用模式

### 基本查询模式

```mermaid
graph TD
    A[初始化浏览器] --> B[创建 Page 对象]
    B --> C[wrap 包装 Page]
    C --> D[定义 AgentQL 查询]
    D --> E[queryData 执行查询]
    E --> F[处理返回数据]
```

### 基础示例

```javascript
const { wrap, configure } = require('agentql');
const { chromium } = require('playwright');

const URL = 'https://example.com';

async function main() {
    // 1. 配置 API
    configure({ apiKey: process.env.AGENTQL_API_KEY });
    
    // 2. 启动浏览器
    const browser = await chromium.launch({ headless: false });
    const page = await wrap(await browser.newPage());
    
    // 3. 导航到目标页面
    await page.goto(URL);
    
    // 4. 执行查询
    const QUERY = `{ headline title }`;
    const data = await page.queryData(QUERY);
    console.log(data);
    
    // 5. 关闭浏览器
    await browser.close();
}

main();
```

### 分页数据采集模式

对于需要遍历多页的场景：

```javascript
const QUERY = `
{
    books[] {
        name
        price
        rating
    }
}`;

const books = [];
const browser = await chromium.launch({ headless: false });
const page = await wrap(await browser.newPage());

await page.goto(URL);

while (books.length < 50) {
    const response = await page.queryData(QUERY);
    books.push(...response.books);
    
    // 检查是否有下一页
    if (paginationInfo.hasNextPage) {
        await goToTheNextPage(page, URL);
    }
}
```

资料来源：[examples/js/collect-paginated-ecommerce-data/main.js:1-26]()

### 价格筛选模式

```javascript
async function searchProduct(page, product, minPrice, maxPrice) {
    // 使用 getByPrompt 定位搜索输入框
    const searchInput = await page.getByPrompt('the search input field');
    await searchInput.type(product, { delay: 200 });
    await searchInput.press('Enter');

    // 定位价格筛选输入框
    const minPriceInput = await page.getByPrompt('the min price input field');
    await minPriceInput.fill(String(minPrice));

    const maxPriceInput = await page.getByPrompt('the max price input field');
    await maxPriceInput.fill(String(maxPrice));
    await maxPriceInput.press('Enter');
    return true;
}
```

资料来源：[examples/js/collect-pricing-data/main.js:16-33]()

### 数据提取与转换

AgentQL 查询语言支持在查询时直接进行数据转换：

```javascript
const QUERY = `
{
    items[]
    {
        published_date(convert to XX/XX/XXXX format)
        entry(title or post if no title is available)
        author(person's name; return "n/a" if not available)
        outlet(the original platform it is posted on)
        url
    }
}`;
```

资料来源：[examples/js/news-aggregator/main.js:8-15]()

## 查询语法参考

### 列表查询

使用 `[]` 语法声明列表类型：

```
{
    products[] {
        name
        price
    }
}
```

### 数据转换指令

在字段名后添加括号指定转换规则：

| 转换指令 | 示例 | 说明 |
|---------|------|------|
| 类型转换 | `price(integer)` | 将价格转换为整数 |
| 格式化 | `date(convert to XX/XX/XXXX)` | 格式化日期输出 |
| 条件返回 | `author(return "n/a" if not available)` | 提供默认值 |

### 自然语言选择器

通过描述性语言定位元素：

| 提示文本 | 定位目标 |
|---------|---------|
| `Sign up button` | 注册按钮 |
| `the search input field` | 搜索输入框 |
| `the min price input field` | 最低价输入框 |

## 高级用法

### 并发数据采集

利用 Playwright 的上下文功能实现多标签页并发：

```javascript
async function fetchData(context, url) {
    const page = await wrap(await context.newPage());
    await page.goto(url);
    return await page.queryData(QUERY);
}

// 在同一浏览器上下文中打开多个标签页
await asyncio.gather(
    *(fetchData(context, url) for url in WEBSITE_URLS)
);
```

### 与 Playwright 原生 API 混用

包装后的 Page 对象仍可调用所有 Playwright 原生方法：

```javascript
const wrappedPage = await wrap(page);

// AgentQL 方法
await wrappedPage.queryData(QUERY);

// Playwright 原生方法
await wrappedPage.waitForTimeout(10000);
await wrappedPage.screenshot({ path: 'screenshot.png' });
```

## 已知限制

### Cloudflare 边缘环境

社区反馈表明，JavaScript SDK 在 Cloudflare Workers 等边缘环境中使用时存在兼容性问题。边缘环境对部分 Node.js API 有限制，而 SDK 依赖这些 API 进行正常工作。详情见 [Issue #128](https://github.com/tinyfish-io/agentql/issues/128)。

### 元素定位准确性

某些情况下，查询结果可能返回无用的 span 元素而非预期的目标元素。社区已在 [Issue #121](https://github.com/tinyfish-io/agentql/issues/121) 中报告了此问题，涉及特定网站如 CheckPoint Careers 页面。

## 相关资源

| 资源类型 | 链接 |
|---------|------|
| 官方文档 | [JavaScript SDK 安装指南](https://docs.agentql.com/javascript-sdk/installation) |
| 示例代码 | [examples/js](https://github.com/tinyfish-io/agentql/tree/main/examples/js) |
| Chrome 调试器 | [AgentQL Debugger 扩展](https://chromewebstore.google.com/detail/agentql-debugger/idnejmodeepdobpinkkgpkeabkabhhej) |
| Playground | [AgentQL Playground](https://playground.agentql.com/) |

---

<a id='debugger-extension'></a>

## 浏览器调试器扩展

### 相关页面

相关主题：[Python SDK 详解](#python-sdk), [JavaScript SDK 详解](#javascript-sdk)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/python/list_query_usage/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/README.md)
- [examples/js/list-query-usage/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/list-query-usage/README.md)
- [examples/python/collect_paginated_news_headlines/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/collect_paginated_news_headlines/README.md)
- [examples/js/collect-paginated-news-headlines/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-paginated-news-headlines/README.md)
- [examples/python/news-aggregator/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/README.md)
- [examples/js/news-aggregator/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/news-aggregator/README.md)
- [examples/python/first_steps/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)
</details>

# 浏览器调试器扩展

## 概述

AgentQL 浏览器调试器扩展（AgentQL Debugger Chrome Extension）是一款 Chrome 浏览器插件，旨在帮助开发者交互式地构建、测试和调试 AgentQL 查询语句。该扩展通过可视化的方式让用户在浏览器中直接编写和验证查询语句，显著降低了学习和使用 AgentQL 的门槛。

### 核心功能

| 功能 | 描述 |
|------|------|
| 交互式查询编写 | 在任意网页上实时编写和测试 AgentQL 查询 |
| 查询预览 | 即时查看查询返回的数据结构 |
| 自然语言选择器支持 | 通过自然语言描述定位页面元素 |
| 跨浏览器一致性 | 确保查询在不同浏览器环境下行为一致 |

资料来源：[examples/python/list_query_usage/README.md:14](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/README.md)

## 工作原理

### 架构流程

```mermaid
graph TD
    A[用户访问网页] --> B[激活调试器扩展]
    B --> C[编写 AgentQL 查询]
    C --> D[扩展执行查询]
    D --> E[Playwright 渲染页面]
    E --> F[LLM 解析查询意图]
    F --> G[返回匹配元素]
    G --> H[展示查询结果]
    H --> I{结果是否满意?}
    I -->|是| J[复制查询到代码]
    I -->|否| C
```

### 查询执行流程

当用户在调试器扩展中执行查询时，系统会经历以下步骤：

1. **页面加载** - Playwright 加载目标网页
2. **查询解析** - LLM 解析 AgentQL 查询语句
3. **元素定位** - 根据查询语义定位页面 DOM 元素
4. **数据提取** - 提取匹配元素的数据
5. **结果展示** - 在扩展界面中展示提取结果

资料来源：[examples/python/first_steps/main.py:25-30](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

## 安装指南

### 系统要求

| 要求类型 | 最低版本 |
|---------|---------|
| Chrome 浏览器 | 88.0+ |
| 网络连接 | 需要（访问扩展商店） |

### 安装步骤

1. 访问 [AgentQL Chrome 扩展安装页面](https://docs.agentql.com/installation/chrome-extension-installation)
2. 点击"添加到 Chrome"按钮
3. 在弹出对话框中确认安装
4. 安装完成后，扩展图标将出现在浏览器工具栏

资料来源：[examples/js/list-query-usage/README.md:15-17](https://github.com/tinyfish-io/agentql/blob/main/examples/js/list-query-usage/README.md)

## 使用方法

### 基本工作流程

```mermaid
graph LR
    A[打开目标网页] --> B[点击扩展图标]
    B --> C[输入查询语句]
    C --> D[点击执行]
    D --> E[查看结果]
    E --> F[调整查询]
    F --> C
```

### 查询编写示例

以下是一个典型的查询编写流程：

**步骤 1：定位搜索框**

```agentql
{
    search_product_box
}
```

**步骤 2：提取产品数据**

```agentql
{
    price_currency
    products[] {
        name
        price(integer)
    }
}
```

**步骤 3：使用自然语言选择器**

```
NATURAL_LANGUAGE_PROMPT = "Button to display Qwilfish page"
```

资料来源：[examples/python/first_steps/main.py:20-42](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

### 在示例项目中的应用

所有 AgentQL 示例项目都推荐使用调试器扩展来优化查询。以下是常见的使用场景：

#### 分页数据采集

```agentql
{
    items(might be articles, posts, tweets)[]{
        published_date(convert to XX/XX/XXXX format)
        entry(title or post if no title is available)
        author(person's name; return "n/a" if not available)
        outlet(the original platform it is posted on)
        url
    }
}
```

资料来源：[examples/python/news-aggregator/README.md:21-31](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/README.md)

#### 列表项查询

```agentql
{
    items_list[] {
        item_name
        item_description
        item_price
    }
}
```

资料来源：[examples/python/list_query_usage/README.md:18-24](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/README.md)

## 最佳实践

### 查询优化建议

| 建议 | 说明 |
|------|------|
| 使用描述性名称 | 为提取字段使用清晰的名称 |
| 明确数据类型 | 使用类型转换如 `(integer)` 确保数据类型正确 |
| 限制结果范围 | 避免一次性提取过多数据 |
| 迭代式开发 | 先编写简单查询，再逐步完善 |

### 常见问题处理

#### 查询元素定位不准确

当遇到查询结果与预期不符时（如元素被解析为无用的 span），建议：

1. 使用更具体的自然语言描述
2. 检查页面结构是否动态加载
3. 尝试使用属性选择器而非内容选择器

资料来源：[github.com/tinyfish-io/agentql/issues/121](https://github.com/tinyfish-io/agentql/issues/121)

### 与 IDE 工作流集成

调试器扩展的最佳实践是与代码编辑器形成完整的工作流：

```mermaid
graph LR
    A[浏览器调试器] --> B[优化查询]
    B --> C[复制到 IDE]
    C --> D[编写脚本]
    D --> E[运行测试]
    E --> F{是否需要调整?}
    F -->|是| A
    F -->|否| G[完成]
```

## 进阶用法

### 自然语言选择器

AgentQL 支持使用自然语言描述来定位元素，这使得查询编写更加直观：

```python
# 示例：定位特定按钮
NATURAL_LANGUAGE_PROMPT = "显示 Qwilfish 页面的按钮"
```

这种方式的优点：

- **跨站点兼容性** - 相同的自然语言描述在不同网站也能工作
- **自愈能力** - 页面结构变化时查询仍能正确执行
- **意图导向** - 基于内容意图而非 DOM 结构

资料来源：[examples/python/first_steps/main.py:44-45](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

### 数据转换与提取

在查询中可以直接进行数据转换：

```agentql
{
    products[] {
        name
        price(integer)          # 转换为整数
        published_date(format: "XX/XX/XXXX")  # 格式化日期
    }
}
```

## 相关资源

| 资源类型 | 链接 |
|---------|------|
| 官方文档 | [AgentQL 文档](https://docs.agentql.com) |
| 安装指南 | [Chrome 扩展安装](https://docs.agentql.com/installation/chrome-extension-installation) |
| 查询语言教程 | [AgentQL 查询入门](https://docs.agentql.com/agentql-query/query-intro) |
| 示例项目 | [Python 示例](https://github.com/tinyfish-io/agentql/tree/main/examples/python) / [JavaScript 示例](https://github.com/tinyfish-io/agentql/tree/main/examples/js) |

## 与其他工具的配合

### 与 Playwright 的协同

调试器扩展与 Playwright SDK 紧密配合：

```python
# 使用调试器验证后的查询
page = agentql.wrap(browser.new_page())
page.goto(URL)

# 使用扩展中测试过的查询
data = page.query_data(QUERY)
```

资料来源：[examples/python/first_steps/main.py:47-52](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

### 与 Cloudflare Browser Rendering 的兼容

社区反馈表明，在 Cloudflare Workers 环境中使用调试器扩展时需要注意：

- Edge 环境对某些 Node.js API 支持有限
- 可能需要调整查询以适应无头浏览器环境

资料来源：[github.com/tinyfish-io/agentql/issues/128](https://github.com/tinyfish-io/agentql/issues/128)

---

<a id='python-examples'></a>

## Python 示例代码集

### 相关页面

相关主题：[JavaScript 示例代码集](#javascript-examples), [高级使用模式](#advanced-patterns), [Python SDK 详解](#python-sdk)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/python/first_steps/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)
- [examples/python/news-aggregator/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)
- [examples/python/news-aggregator/main_sync.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main_sync.py)
- [examples/python/list_query_usage/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/README.md)
- [examples/python/news-aggregator/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/README.md)
- [examples/python/collect_paginated_ecommerce_listing_data/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/collect_paginated_ecommerce_listing_data/README.md)
- [examples/python/collect_paginated_news_headlines/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/collect_paginated_news_headlines/README.md)
- [examples/python/use_existing_browser/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/use_existing_browser/README.md)
</details>

# Python 示例代码集

## 概述

Python 示例代码集是 AgentQL 项目的重要组成部分，提供了使用 Python SDK 进行网页数据提取、自动化测试和浏览器交互的实战示例。这些示例代码覆盖了从基础入门到高级应用的多种场景，帮助开发者快速掌握 AgentQL 的核心功能。

AgentQL Python SDK 与 Playwright 无缝集成，提供了 `agentql.wrap()` 方法来扩展 Playwright 的 Page 对象，使其具备智能定位和数据查询能力。开发者可以通过自然语言查询定位页面元素，定义结构化数据输出，并在查询中应用数据转换。

## 核心功能模块

### 基础查询功能

AgentQL 的核心是 `query_elements()` 和 `query_data()` 两个方法。前者用于定位 DOM 元素，返回可交互的 Playwright 元素对象；后者用于提取结构化数据，支持嵌套对象和数组提取。

```python
# 导入 AgentQL 扩展
import agentql
from agentql.ext.playwright.sync_api import Page
from playwright.sync_api import sync_playwright

# 包装浏览器页面对象
page = agentql.wrap(browser.new_page())

# 使用 AgentQL 查询定位元素
SEARCH_BOX_QUERY = """
{
    search_product_box
}
"""

response = page.query_elements(SEARCH_BOX_QUERY)
response.search_product_box.type("fish", delay=200)

# 提取结构化数据
PRODUCT_DATA_QUERY = """
{
    price_currency
    products[] {
        name
        price(integer)
    }
}
"""

data = page.query_data(PRODUCT_DATA_QUERY)
```

资料来源：[examples/python/first_steps/main.py:1-42](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

### 自然语言定位器

AgentQL 提供了 `get_by_prompt()` 方法，允许开发者使用自然语言描述来定位页面元素。这种方式比传统的 CSS 选择器或 XPath 更加直观，特别适合定位那些结构可能变化但语义保持一致的元素。

```python
# 使用自然语言提示定位元素
NATURAL_LANGUAGE_PROMPT = "Button to display Qwilfish page"
qwilfish_page_btn = page.get_by_prompt(NATURAL_LANGUAGE_PROMPT)
```

资料来源：[examples/python/first_steps/main.py:47-52](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)

## 示例代码分类

### 新闻聚合器

新闻聚合器示例展示了如何从多个新闻网站并发抓取数据并将结果保存为 CSV 文件。该示例提供了异步和同步两种实现方式。

#### 异步实现

异步版本使用 `asyncio.gather()` 并发处理多个 URL，显著提高数据采集效率。

```python
import agentql
from playwright.async_api import async_playwright

WEBSITE_URLS = [
    "https://duckduckgo.com/?q=agents+for+the+web&t=h_&iar=news&ia=news",
]

async def main():
    async with async_playwright() as p:
        async with await p.chromium.launch(headless=True) as browser:
            async with await browser.new_context() as context:
                await asyncio.gather(
                    *(fetch_data(context, url) for url in WEBSITE_URLS)
                )
```

资料来源：[examples/python/news-aggregator/main.py:10-23](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)

#### 同步实现

同步版本按顺序处理 URL，适合需要严格控制请求顺序的场景。

```python
import agentql
from playwright.sync_api import sync_playwright

def main():
    with sync_playwright() as p:
        with p.chromium.launch(headless=True) as browser:
            context = browser.new_context()
            for url in WEBSITE_URLS:
                fetch_data(context, url)
```

资料来源：[examples/python/news-aggregator/main_sync.py:16-24](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main_sync.py)

### 分页数据采集

分页数据采集示例演示了如何遍历多个分页页面收集数据，适用于 HackerNews、电商列表等场景。

| 参数 | 类型 | 说明 |
|------|------|------|
| query | str | AgentQL 查询语句 |
| num_pages | int | 要采集的页数 |
| page | Page | Playwright 页面对象 |

该示例通过循环翻页并累积数据，直到达到指定页数或页面不再包含目标元素。

```python
async def fetch_data(context, query, num_pages):
    page = await agentql.wrap_async(context.new_page())
    all_data = []
    
    for page_num in range(num_pages):
        data = await page.query_data(query)
        all_data.extend(data.get("items", []))
        await page.click("next_button_selector")
        await page.wait_for_load_state("networkidle")
```

资料来源：[examples/python/collect_paginated_news_headlines/README.md:1-25](https://github.com/tinyfish-io/agentql/blob/main/examples/python/collect_paginated_news_headlines/README.md)

### 列表项查询

列表项查询示例展示了如何从页面中提取重复出现的数据结构，如产品列表、新闻条目等。通过在查询中使用 `[]` 语法，AgentQL 可以自动识别并提取数组类型的数据。

```python
LIST_QUERY = """
{
    items[] {
        title
        url
        author
    }
}
"""

data = page.query_data(LIST_QUERY)
# data["items"] 是一个包含所有列表项的数组
```

资料来源：[examples/python/list_query_usage/README.md:1-20](https://github.com/tinyfish-io/agentql/blob/main/examples/python/list_query_usage/README.md)

### 电商数据采集

电商数据采集示例专门针对电商网站的商品列表和分页结构进行了优化，支持提取商品名称、价格、库存等关键信息。

```python
ECOMMERCE_QUERY = """
{
    products[] {
        name
        price(integer)
        availability
        category
    }
    pagination {
        current_page
        total_pages
        next_button
    }
}
"""
```

资料来源：[examples/python/collect_paginated_ecommerce_listing_data/README.md:1-25](https://github.com/tinyfish-io/agentql/blob/main/examples/python/collect_paginated_ecommerce_listing_data/README.md)

### 现有浏览器复用

AgentQL 支持连接到已打开的浏览器实例，这对于调试和手动操作场景特别有用。开发者可以通过 Chrome DevTools Protocol 地址连接到现有浏览器。

```python
from playwright.sync_api import sync_playwright

# 启动带调试端口的浏览器
# google-chrome --remote-debugging-port=9222

browser = p.chromium.connect_over_cdp("http://127.0.0.1:9222")
page = agentql.wrap(browser.new_page())
```

资料来源：[examples/python/use_existing_browser/README.md:1-20](https://github.com/tinyfish-io/agentql/blob/main/examples/python/use_existing_browser/README.md)

## 工作流程架构

```mermaid
graph TD
    A[启动浏览器] --> B[创建 Page 对象]
    B --> C[agentql.wrap 包装]
    C --> D[定义 AgentQL 查询]
    D --> E[query_elements 或 query_data]
    E --> F{查询类型}
    F -->|元素定位| G[返回 Playwright 元素]
    F -->|数据提取| H[返回结构化 JSON]
    G --> I[执行交互操作]
    H --> J[处理和存储数据]
    I --> K[继续导航或关闭]
    J --> K
```

## 数据提取流程

```mermaid
sequenceDiagram
    participant Dev as 开发者
    participant API as AgentQL API
    participant Page as Playwright Page
    participant Target as 目标网页
    
    Dev->>API: 定义 AgentQL 查询
    API->>Page: 发送查询请求
    Page->>Target: 加载页面 DOM
    Target-->>Page: 返回 DOM 结构
    Page->>API: 发送 DOM 数据
    API->>API: 解析并转换数据
    API-->>Dev: 返回结构化结果
```

## 常见使用模式

### 搜索和筛选流程

```python
def search_and_collect(page, search_term, max_results):
    """执行搜索并收集结果"""
    # 定位搜索框
    search_box = page.query_elements('{ search_input }')
    
    # 输入搜索关键词
    search_box.type(search_term)
    page.keyboard.press("Enter")
    
    # 等待结果加载
    page.wait_for_load_state("networkidle")
    
    # 提取搜索结果
    results = page.query_data('''
    {
        search_results[] {
            title
            link
            snippet
        }
    }
    ''')
    
    return results["search_results"]
```

### CSV 数据导出

```python
import os

CSV_FILE_PATH = "output_data.csv"

def save_to_csv(data, fieldnames):
    """保存数据到 CSV 文件"""
    file_exists = os.path.exists(CSV_FILE_PATH)
    
    with open(CSV_FILE_PATH, "a", encoding="utf-8") as file:
        if not file_exists:
            file.write(" | ".join(fieldnames) + "\n")
        
        for item in data:
            clean_entry = str(item).replace("|", "")
            file.write(clean_entry + "\n")
```

资料来源：[examples/python/news-aggregator/main.py:25-45](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)

## 安装和配置

### 环境要求

| 组件 | 最低版本 | 推荐版本 |
|------|----------|----------|
| Python | 3.8 | 3.12+ |
| Playwright | 1.40 | 最新版 |
| AgentQL | - | 最新版 |

### 安装步骤

1. 安装 AgentQL SDK：
```bash
pip install agentql
```

2. 安装浏览器驱动：
```bash
playwright install chromium
```

3. 验证安装：
```bash
python -c "import agentql; print(agentql.__version__)"
```

## 社区反馈与注意事项

根据社区反馈，在使用 AgentQL 进行元素查询时，需要注意以下几点：

- **元素定位问题**：某些网站可能使用复杂的 DOM 结构，查询结果可能定位到无用的 span 元素而非预期元素。遇到此类问题时，可尝试使用更精确的自然语言描述或调整查询语句。
- **分页处理**：对于动态加载的分页内容，需要在翻页后等待网络请求完成再进行数据提取。
- **并发控制**：虽然支持异步并发操作，但建议控制并发数量以避免触发网站的反爬机制。

## 相关资源

- [AgentQL 官方文档](https://docs.agentql.com)
- [Python SDK 安装指南](https://docs.agentql.com/python-sdk/installation)
- [AgentQL 查询语言介绍](https://docs.agentql.com/agentql-query/query-intro)
- [Chrome 调试扩展](https://docs.agentql.com/installation/chrome-extension-installation)
- [Discord 社区支持](https://discord.gg/agentql)

---

<a id='javascript-examples'></a>

## JavaScript 示例代码集

### 相关页面

相关主题：[Python 示例代码集](#python-examples), [JavaScript SDK 详解](#javascript-sdk), [Cloudflare 浏览器渲染集成](#cloudflare-integration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/js/get-by-prompt/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/get-by-prompt/main.js)
- [examples/js/collect-pricing-data/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-pricing-data/main.js)
- [examples/js/news-aggregator/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/news-aggregator/main.js)
- [examples/js/collect-paginated-news-headlines/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-paginated-news-headlines/main.js)
- [examples/js/collect-paginated-ecommerce-data/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/js/collect-paginated-ecommerce-data/README.md)
- [examples/js/package.json](https://github.com/tinyfish-io/agentql/blob/main/examples/js/package.json)
</details>

# JavaScript 示例代码集

JavaScript 示例代码集是 AgentQL 项目为 JavaScript/Node.js 开发者提供的一套完整示例脚本集合，涵盖数据采集、页面自动化、情感分析等常见场景。这些示例演示了如何使用 AgentQL JavaScript SDK 与 Playwright 无缝集成，实现 AI 驱动的网页交互和数据提取。

## 核心依赖环境

JavaScript 示例基于以下核心依赖构建：

| 依赖包 | 版本要求 | 用途 |
|--------|----------|------|
| agentql | latest | AgentQL SDK 核心库 |
| playwright | ^1.48.2 | 浏览器自动化框架 |
| openai | ^4.70.1 | GPT 模型集成（用于高级分析场景） |
| playwright-dompath | ^0.0.7 | DOM 路径解析扩展 |

资料来源：[examples/js/package.json:10-15]()

## SDK 核心 API

JavaScript SDK 提供两个主要导出函数：

```javascript
const { wrap, configure } = require('agentql');
```

| API | 说明 |
|-----|------|
| `wrap(page)` | 将 Playwright Page 对象包装为 AgentQL 增强页面，支持查询方法 |
| `configure({ apiKey })` | 配置 AgentQL API 密钥（可省略，默认使用环境变量） |

资料来源：[examples/js/get-by-prompt/main.js:4-5]()

## 示例脚本分类

### 1. 按提示词定位元素

`get-by-prompt` 示例展示了如何使用自然语言提示词定位页面元素：

```javascript
// 获取 "Sign up" 提示的按钮
const signUpBtn = await page.getByPrompt('Sign up button');
if (signUpBtn) {
  await signUpBtn.click();
}
```

此方法通过自然语言描述定位元素，无需编写 CSS 选择器或 XPath，适用于 UI 结构频繁变化的场景。

资料来源：[examples/js/get-by-prompt/main.js:24-28]()

### 2. 数据查询与转换

`collect-pricing-data` 示例演示了复杂的数据查询与转换能力：

```javascript
const QUERY = `
  {
      products[] {
          name
          model
          sku
          price(integer)  // 类型转换 transform
      }
  }`;
const pricingData = await page.queryData(QUERY);
```

AgentQL 查询语言支持以下特性：

- **列表提取**：使用 `[]` 语法提取数组数据
- **类型转换**：在字段后添加 `(integer)` 等类型指示器进行数据转换
- **嵌套结构**：支持多层级数据结构查询

资料来源：[examples/js/collect-pricing-data/main.js:9-17]()

### 3. 分页数据采集

分页采集是网页数据抓取中的常见需求，AgentQL 提供了两种实现模式：

#### 新闻分页采集

`collect-paginated-news-headlines` 使用 End 键滚动方式触发分页加载：

```javascript
const paginationQuery = `
  {
      pagination {
          next_button
      }
  }`;

// 按 End 键滚动到页面底部加载下一页
await page.keyboard.press('End');
```

#### 电商分页采集

`collect-paginated-ecommerce-data` 采用类似模式，但针对电商页面结构优化：

```mermaid
graph TD
    A[打开商品列表页] --> B[执行数据查询]
    B --> C{判断是否有下一页}
    C -->|是| D[点击下一页按钮]
    C -->|否| E[保存数据]
    D --> B
    E --> F[结束采集]
```

两种模式的选择取决于目标网站的加载机制：

| 滚动方式 | 适用场景 | 实现难度 |
|----------|----------|----------|
| 按键滚动 (End) | 无限滚动页面 | 简单 |
| 点击按钮 | 传统分页导航 | 中等 |

资料来源：[examples/js/collect-paginated-news-headlines/main.js]()
资料来源：[examples/js/collect-paginated-ecommerce-data/README.md]()

### 4. 新闻聚合器

`news-aggregator` 示例展示了多标签页并发数据采集能力：

```javascript
const websiteUrls = [
  'https://bsky.app/search?q=agents+for+the+web',
  'https://dev.to/search?q=agents%20for%20the+web',
  'https://hn.algolia.com/?dateRange=last24h&query=agents',
  'https://duckduckgo.com/?q=agents+for+the+web&iar=news&ia=news',
];

// 并发处理多个 URL
await asyncio.gather(
  *(fetchData(context, url) for url in websiteUrls)
);
```

此模式在单一浏览器上下文中创建多个标签页，实现高效的并发数据采集。

资料来源：[examples/js/news-aggregator/main.js:13-18]()

### 5. 情感分析集成

`perform_sentiment_analysis` 示例（位于 Python 示例中）展示了将 AgentQL 与 OpenAI GPT-3.5 结合的高级用法，通过提取页面数据后进行 AI 驱动的语义分析。

## 执行流程架构

```mermaid
graph TD
    A[配置 API Key] --> B[启动 Chromium 浏览器]
    B --> C[创建 Page 对象]
    C --> D[使用 wrap 包装页面]
    D --> E[导航到目标 URL]
    E --> F[执行 AgentQL 查询]
    F --> G[获取结构化数据]
    G --> H{处理完成?}
    H -->|否| F
    H -->|是| I[关闭浏览器]
    I --> J[数据后处理]
```

## 常见问题与社区反馈

### Cloudflare Edge 环境兼容性

社区 Issue #128 讨论了 AgentQL JavaScript SDK 在 Cloudflare Workers 边缘环境中使用时的限制。由于边缘环境不支持部分 Node.js API，可能需要调整实现方式。

### 元素定位准确性

Issue #121 报告了某些网站中查询结果定位不准确的问题，建议使用 Chrome 扩展调试器调整查询语句以获得更精确的定位。

## 快速开始

1. 安装依赖：

```bash
npm install agentql playwright openai
```

2. 配置环境变量：

```bash
export AGENTQL_API_KEY="your-api-key"
```

3. 运行示例脚本：

```bash
node main.js
```

## 相关资源

- [JavaScript SDK 安装文档](https://docs.agentql.com/javascript-sdk/installation)
- [AgentQL 查询语言参考](https://docs.agentql.com/agentql-query/query-intro)
- [Chrome 调试器扩展](https://docs.agentql.com/installation/chrome-extension-installation)

---

<a id='advanced-patterns'></a>

## 高级使用模式

### 相关页面

相关主题：[Python 示例代码集](#python-examples), [JavaScript 示例代码集](#javascript-examples), [Cloudflare 浏览器渲染集成](#cloudflare-integration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/python/use_remote_browser/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/use_remote_browser/main.py)
- [examples/python/use_existing_browser/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/use_existing_browser/main.py)
- [examples/python/stealth_mode/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/stealth_mode/main.py)
- [examples/python/save_and_load_authenticated_session/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/save_and_load_authenticated_session/main.py)
- [examples/js/use-remote-browser/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/use-remote-browser/main.js)
- [examples/js/use-existing-browser/main.js](https://github.com/tinyfish-io/agentql/blob/main/examples/js/use-existing-browser/main.js)
</details>

# 高级使用模式

AgentQL 提供了多种高级使用模式，使开发者能够应对复杂的网页自动化和数据提取场景。这些模式扩展了基础的查询功能，支持远程浏览器连接、现有浏览器复用、隐身模式以及会话持久化等高级特性。

## 功能概览

| 使用模式 | 用途 | 主要优势 |
|----------|------|----------|
| 远程浏览器 | 连接外部运行的浏览器实例 | 复用已打开的浏览器状态，节省资源 |
| 现有浏览器 | 操控用户已打开的浏览器页面 | 无需重新登录，支持已认证会话 |
| 隐身模式 | 隐藏自动化特征避免检测 | 提高爬虫成功率，降低被封禁风险 |
| 会话持久化 | 保存和恢复认证状态 | 跨会话保持登录状态 |

## 远程浏览器模式

### 工作原理

远程浏览器模式允许 AgentQL 通过 Chrome DevTools Protocol (CDP) 连接到已经运行的浏览器实例。这种方式避免了每次都启动新浏览器的开销，特别适用于需要复用复杂登录状态的场景。

```mermaid
graph TD
    A[启动浏览器<br/>--remote-debugging-port=9222] --> B[AgentQL 通过 CDP 连接]
    B --> C[获取已打开页面列表]
    C --> D[选择目标页面]
    D --> E[执行 AgentQL 查询]
    E --> F[提取数据]
```

### Python 实现

```python
from agentql.ext.playwright.sync_api import sync_playwright
import agentql

async def main():
    async with sync_playwright() as p:
        # 通过 CDP URL 连接到远程浏览器
        browser = await p.chromium.connect_over_cdp(
            "http://127.0.0.1:9222"
        )
        
        # 获取所有打开的页面
        contexts = browser.contexts
        if contexts:
            page = contexts[0].pages[0]
            wrapped_page = agentql.wrap(page)
            
            # 执行查询
            data = await wrapped_page.query_data(QUERY)
```

### 连接参数说明

| 参数 | 类型 | 说明 |
|------|------|------|
| `endpoint` | string | CDP 端点 URL，如 `http://127.0.0.1:9222` |
| `headers` | dict | 可选的 HTTP 请求头 |
| `slow_mo` | int | 每次操作的延迟毫秒数，用于调试 |

## 现有浏览器模式

### 核心概念

现有浏览器模式使开发者能够直接操控用户已打开的浏览器页面。通过 AgentQL Debugger Chrome 扩展打开的页面可以作为数据源，无需重新导航和认证。

这种模式特别适用于以下场景：

- 用户已在浏览器中登录网站
- 需要从复杂单页应用中提取数据
- 需要复用已有的浏览器状态

```mermaid
graph LR
    A[用户在浏览器中<br/>打开目标页面] --> B[安装 AgentQL<br/>Chrome 扩展]
    B --> C[点击扩展图标<br/>启动调试模式]
    C --> D[运行 Python 脚本<br/>连接本地浏览器]
    D --> E[执行查询<br/>提取数据]
```

### 使用限制

现有浏览器模式依赖本地 Chrome 实例和特定的启动参数。脚本启动时会输出调试端点 URL，用户需要在终端中复制该 URL 并在浏览器中访问以建立连接。

资料来源：[examples/python/use_existing_browser/main.py:1-20]()

## 隐身模式

### 功能特性

隐身模式通过隐藏常见的自动化特征来避免被网站检测。这些特征包括：

- 移除 webdriver 属性
- 修改 navigator 对象
- 模拟真实用户代理
- 禁用某些 JavaScript API 检测

### 启用方式

```python
import agentql

with sync_playwright() as p:
    browser = await p.chromium.launch(
        headless=True,
        args=[
            "--disable-blink-features=AutomationControlled"
        ]
    )
    
    page = agentql.wrap(browser.new_page())
    # 隐身模式自动应用
    page.goto(url)
```

隐身模式集成在 AgentQL 的页面包装机制中，无需额外配置即可自动生效。这种设计确保了在进行大规模数据抓取时的隐蔽性。

## 会话持久化

### 工作流程

会话持久化功能允许开发者保存当前的浏览器状态（Cookie、Local Storage、会话数据）并在后续运行中恢复。这对于需要长期维护登录状态的自动化任务至关重要。

```mermaid
graph TD
    A[首次运行<br/>完整登录流程] --> B[保存会话状态]
    B --> C[存储到本地文件]
    C --> D[后续运行]
    D --> E[加载会话状态]
    E --> F[跳过登录<br/>直接访问目标页面]
```

### 实现示例

```python
import json
import agentql
from pathlib import Path

STORAGE_STATE_PATH = Path(__file__).parent / "state.json"

def main():
    with sync_playwright() as p:
        context = p.chromium.launch_persistent_context(
            user_data_dir="./user_data_dir"
        )
        
        page = agentql.wrap(context.pages[0])
        page.goto("https://example.com")
        
        # 执行登录操作
        perform_login(page)
        
        # 保存状态
        state = context.storage_state()
        with open(STORAGE_STATE_PATH, 'w') as f:
            json.dump(state, f)

def load_session():
    with open(STORAGE_STATE_PATH) as f:
        state = json.load(f)
    return state
```

### 状态管理参数

| 参数 | 说明 |
|------|------|
| `cookies` | 包含名称、值、域、路径等信息的 Cookie 数组 |
| `origins` | Local Storage 和 Session Storage 数据 |
| `storage_state` | Playwright 的标准存储状态格式 |

## 社区相关讨论

### 已知问题与解决方案

**远程浏览器在 Cloudflare 环境中的限制**

社区 issue #128 讨论了 AgentQL JavaScript SDK 与 Cloudflare Browser Rendering 服务的集成问题。Cloudflare Workers 环境对某些 Node.js API 有限制，可能影响远程浏览器连接的稳定性。

**元素定位不准确问题**

issue #121 报告了某些网站（如 Checkpoint 招聘页面）上查询结果不准确的问题。元素可能被解析为无用的 span 标签而非预期的元素。这种情况下建议使用更精确的 AgentQL 查询或结合传统 CSS 选择器。

### 文档链接问题

issue #64 指出官方文档中的 Google Colab 示例链接指向了错误的目录。正确的路径应为 `examples/run_script_online_in_google_colab`。

## 最佳实践

### 浏览器资源管理

| 场景 | 建议 |
|------|------|
| 频繁重启 | 使用远程浏览器模式复用连接 |
| 单次任务 | 使用隐身模式提高成功率 |
| 长期任务 | 结合会话持久化避免重复认证 |

### 错误处理

```python
from playwright.sync_api import Error as PlaywrightError

try:
    browser = p.chromium.connect_over_cdp(endpoint)
except PlaywrightError as e:
    logger.error(f"无法连接到远程浏览器: {e}")
    # 降级到本地浏览器启动
    browser = p.chromium.launch()
```

## 相关资源

- [AgentQL 官方文档](https://docs.agentql.com)
- [Playwright 浏览器连接指南](https://playwright.dev/docs/api/class-browsertype#browser-type-connect-over-cdp)
- [Chrome DevTools Protocol 文档](https://chromedevtools.github.io/devtools-protocol/)

---

<a id='integrations'></a>

## 第三方集成

### 相关页面

相关主题：[Python SDK 详解](#python-sdk), [JavaScript SDK 详解](#javascript-sdk), [Cloudflare 浏览器渲染集成](#cloudflare-integration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)
- [examples/js/package.json](https://github.com/tinyfish-io/agentql/blob/main/examples/js/package.json)
- [examples/python/news-aggregator/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)
- [examples/python/perform_sentiment_analysis/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/perform_sentiment_analysis/main.py)
- [golden-images.yaml](https://github.com/tinyfish-io/agentql/blob/main/golden-images.yaml)
</details>

# 第三方集成

## 概述

AgentQL 通过丰富的第三方集成生态系统，将 AI 代理与整个 Web 环境连接起来。项目的集成策略围绕核心自动化框架展开，同时支持与主流 AI 服务、代理框架和云平台的深度整合。

根据官方文档，AgentQL 的主要集成包括：

- **Playwright** - 底层浏览器自动化引擎
- **LangChain** - AI 代理框架
- **Zapier** - 工作流自动化平台
- **MCP Server** - 模型上下文协议服务器

资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

---

## Playwright 集成

### 核心地位

Playwright 是 AgentQL 的核心依赖，为所有浏览器自动化操作提供底层支持。AgentQL 提供独立的 Python SDK 和 JavaScript SDK，二者均无缝集成 Playwright 功能。

### SDK 架构

```mermaid
graph TD
    A[用户代码] --> B[AgentQL SDK]
    B --> C[Playwright API]
    C --> D[Chromium / Firefox / WebKit]
    C --> E[浏览器上下文]
    D --> F[网页 DOM]
```

### 安装与配置

**Python SDK：**

```python
pip install agentql playwright
playwright install chromium
```

**JavaScript SDK：**

```json
{
  "dependencies": {
    "agentql": "latest",
    "playwright": "^1.48.2",
    "playwright-dompath": "^0.0.7"
  }
}
```

资料来源：[examples/js/package.json:1-24](https://github.com/tinyfish-io/agentql/blob/main/examples/js/package.json)

### 同步与异步模式

AgentQL 支持同步和异步两种执行模式：

| 模式 | Python | JavaScript |
|------|--------|------------|
| 同步 | `sync_playwright()` | - |
| 异步 | `async_playwright()` | `async/await` |
| 包装函数 | `agentql.wrap()` | - |
| 异步包装 | `agentql.wrap_async()` | - |

**异步示例（Python）：**

```python
from playwright.async_api import async_playwright
import agentql

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        page = await agentql.wrap_async(context.new_page())
        await page.goto("https://example.com")
        data = await page.query_data(QUERY)
```

**同步示例（Python）：**

```python
from playwright.sync_api import sync_playwright
import agentql

def main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context()
        page = agentql.wrap(context.new_page())
        page.goto("https://example.com")
        data = page.query_data(QUERY)
```

资料来源：[examples/python/news-aggregator/main.py:1-50](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)

---

## AI/LLM 集成

### OpenAI 集成

AgentQL 常与 OpenAI 服务结合使用，实现基于 AI 的数据分析功能。通过提取网页数据后，可将结果发送至 GPT 模型进行情感分析、摘要生成等高级处理。

### 情感分析示例

```python
import os
from openai import OpenAI

def perform_sentiment_analysis(comments):
    """对提取的评论进行情感分析。"""
    USER_MESSAGE = "以下是从视频中提取的评论，请分析其情感倾向。"
    
    for comment in comments["comments"]:
        USER_MESSAGE += comment["comment_text"]
    
    SYSTEM_MESSAGE = """你是社交媒体分析专家，专门分析评论的情感倾向。"""
    
    client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
    
    completion = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": SYSTEM_MESSAGE},
            {"role": "user", "content": USER_MESSAGE},
        ],
    )
    
    return completion.choices[0].message.content
```

**JavaScript 版本：**

```javascript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const completion = await client.chat.completions.create({
  model: "gpt-3.5-turbo",
  messages: [
    { role: "system", content: SYSTEM_MESSAGE },
    { role: "user", content: USER_MESSAGE },
  ],
});
```

资料来源：[examples/python/perform_sentiment_analysis/main.py:1-45](https://github.com/tinyfish-io/agentql/blob/main/examples/python/perform_sentiment_analysis/main.py)

### 数据处理流程

```mermaid
graph LR
    A[网页数据提取] --> B[AgentQL query_data]
    B --> C[结构化 JSON 数据]
    C --> D[OpenAI API]
    D --> E[GPT 模型处理]
    E --> F[分析结果输出]
```

---

## 云端浏览器渲染集成

### Cloudflare Browser Rendering

AgentQL JavaScript SDK 支持与 Cloudflare Workers 的 Browser Rendering 功能集成，允许在边缘计算环境中执行浏览器自动化任务。

**已知限制：**

Cloudflare Workers 是边缘执行环境，存在以下 Node.js 兼容性限制：

| 功能 | 状态 | 说明 |
|------|------|------|
| 标准 Playwright API | ✅ 支持 | 核心功能可用 |
| Node.js 特定模块 | ❌ 不支持 | 边缘环境限制 |
| 长时间运行任务 | ⚠️ 受限 | Workers 超时限制 |

资料来源：[#128: AgentQL (JS) x Cloudflare's Browser Rendering](https://github.com/tinyfish-io/agentql/issues/128)

---

## 代理框架集成

### LangChain 集成

AgentQL 被设计为可与 LangChain 代理框架协同工作，使 AI 代理能够通过自然语言查询与动态网页内容交互。

### MCP Server 集成

AgentQL 提供 MCP（Model Context Protocol）服务器实现，允许 AI 模型通过标准化协议访问网页自动化能力：

```
AgentQL MCP Server <---> AI Agent <---> LangChain / 其他框架
```

### Zapier 集成

通过 Zapier 集成，用户可以将 AgentQL 的网页数据提取能力嵌入到自动化工作流中，无需编写代码即可实现复杂的数据收集流程。

资料来源：[README.md](https://github.com/tinyfish-io/agentql/blob/main/README.md)

---

## Docker 运行环境

### 官方基础镜像

AgentQL 项目维护了经过优化的 Docker 运行环境配置：

| 镜像类型 | Python 版本 | 基础系统 | 用途 |
|----------|-------------|----------|------|
| 推荐 | Python 3.13 | Debian 12 (Bookworm) slim | 生产环境 |
| 可用 | Python 3.12 | Debian 12 (Bookworm) slim | 兼容性场景 |

**镜像规格：**

- 运行时版本：3.13.x / 3.12.x
- 最小化安装，减少攻击面
- 完全兼容 pip 包管理

资料来源：[golden-images.yaml:1-30](https://github.com/tinyfish-io/agentql/blob/main/golden-images.yaml)

---

## 依赖管理

### JavaScript 依赖配置

```json
{
  "dependencies": {
    "agentql": "latest",
    "playwright": "^1.48.2",
    "playwright-dompath": "^0.0.7",
    "openai": "^4.70.1"
  },
  "overrides": {
    "axios": "^1.15.0",
    "flatted": "^3.4.2",
    "follow-redirects": "^1.16.0",
    "lodash": "^4.18.0",
    "minimatch": "^3.1.3"
  }
}
```

### 版本覆盖策略

项目使用 `overrides` 字段确保传递依赖的安全版本，防止依赖链中的安全漏洞：

| 依赖包 | 锁定版本 | 原因 |
|--------|----------|------|
| axios | ^1.15.0 | 安全漏洞修复 |
| flatted | ^3.4.2 | 序列化问题 |
| follow-redirects | ^1.16.0 | 重定向安全 |
| lodash | ^4.18.0 | 原型污染修复 |
| minimatch | ^3.1.3 | ReDoS 漏洞 |

资料来源：[examples/js/package.json:15-22](https://github.com/tinyfish-io/agentql/blob/main/examples/js/package.json)

---

## 常见集成场景

### 场景一：多标签页并发数据采集

```mermaid
graph TD
    A[URL 列表] --> B[BrowserContext]
    B --> C[Tab 1]
    B --> D[Tab 2]
    B --> E[Tab N]
    C --> F[AgentQL Query]
    D --> F
    E --> F
    F --> G[CSV 文件聚合]
```

### 场景二：分页数据遍历

适用于电商列表、新闻分页等需要翻页的场景：

```python
async def collect_paginated_data(page, max_pages=5):
    all_items = []
    for i in range(max_pages):
        data = await page.query_data(QUERY)
        all_items.extend(data["items"])
        await page.click("[data-testid='next-button']")
    return all_items
```

### 场景三：已打开页面的数据提取

支持连接用户已打开的浏览器实例：

```python
# 通过 CDP 端点连接已有浏览器
browser_url = "ws://127.0.0.1:9222/devtools/browser/<id>"
page = agentql.wrap(context.new_page())
```

资料来源：[examples/python/use_existing_browser/README.md](https://github.com/tinyfish-io/agentql/blob/main/examples/python/use_existing_browser/README.md)

---

## 社区反馈与已知问题

### 相关 Issue

| Issue | 主题 | 状态 |
|-------|------|------|
| #128 | Cloudflare Browser Rendering 集成 | 讨论中 |
| #153 | run.pay 支付集成建议 | 建议中 |

### 集成最佳实践

1. **版本兼容性**：始终使用 Playwright 的最新稳定版本
2. **错误处理**：为网络超时和页面加载失败添加重试机制
3. **资源清理**：使用上下文管理器确保浏览器资源正确释放
4. **API 密钥管理**：通过环境变量存储敏感信息，避免硬编码

---

<a id='cloudflare-integration'></a>

## Cloudflare 浏览器渲染集成

### 相关页面

相关主题：[JavaScript SDK 详解](#javascript-sdk), [高级使用模式](#advanced-patterns)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/js/package.json](https://github.com/tinyfish-io/agentql/blob/main/examples/js/package.json)
- [examples/python/first_steps/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/first_steps/main.py)
- [examples/python/news-aggregator/main.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main.py)
- [examples/python/news-aggregator/main_sync.py](https://github.com/tinyfish-io/agentql/blob/main/examples/python/news-aggregator/main_sync.py)
- [golden-images.yaml](https://github.com/tinyfish-io/agentql/blob/main/golden-images.yaml)
</details>

# Cloudflare 浏览器渲染集成

## 概述

Cloudflare 浏览器渲染集成是指将 AgentQL 与 Cloudflare Workers 平台上的 Browser Rendering 功能结合使用的技术方案。该集成允许开发者在 Cloudflare 的边缘计算环境中运行基于 Playwright 的浏览器自动化任务，并利用 AgentQL 的自然语言查询能力从网页中提取结构化数据。

根据社区反馈（Issue #128），这一集成面临一些边缘环境特有的技术挑战，需要开发者在使用时注意 Node.js 兼容性限制。

## 架构设计

### 整体架构

```mermaid
graph TD
    A[Cloudflare Worker] --> B[Browser Rendering API]
    B --> C[Playwright 实例]
    C --> D[AgentQL 查询引擎]
    D --> E[结构化数据输出]
    
    F[传统 Node.js 环境] --> G[完整 Playwright 支持]
    G --> H[AgentQL 完整功能]
```

### 集成层级

| 层级 | 组件 | 描述 |
|------|------|------|
| 应用层 | Cloudflare Worker | 边缘计算运行时环境 |
| 渲染层 | Browser Rendering | Cloudflare 提供的浏览器实例管理 |
| 自动化层 | Playwright | 跨浏览器自动化框架 |
| 查询层 | AgentQL | 自然语言查询和数据提取 |

## 核心依赖配置

### JavaScript SDK 依赖

在 `examples/js/package.json` 中定义了 AgentQL JavaScript SDK 的核心依赖：

```json
{
  "dependencies": {
    "agentql": "latest",
    "openai": "^4.70.1",
    "playwright": "^1.48.2",
    "playwright-dompath": "^0.0.7"
  }
}
```

资料来源：[examples/js/package.json:14-18]()

### Python SDK 与 Playwright

Python 版本使用同步或异步 Playwright API：

```python
import agentql
from agentql.ext.playwright.sync_api import Page
from playwright.sync_api import sync_playwright
```

资料来源：[examples/python/first_steps/main.py:1-4]()

## 使用模式

### 同步查询模式

适用于传统的服务器端环境：

```python
from agentql import wrap

page = wrap(browser.new_page())
data = page.query_data(QUERY)
```

### 异步查询模式

适用于高并发的边缘环境：

```python
async with async_playwright() as p:
    page = await agentql.wrap_async(context.new_page())
    data = await page.query_data(QUERY)
```

资料来源：[examples/python/news-aggregator/main.py:1-40]()

## Cloudflare 边缘环境限制

### Node.js 兼容性挑战

根据社区 Issue #128 的讨论，在 Cloudflare Workers 边缘环境中存在以下限制：

| 限制类型 | 具体问题 | 影响范围 |
|----------|----------|----------|
| 全局对象限制 | 某些 Node.js 全局对象不可用 | `process`, `Buffer`, `setImmediate` |
| 模块系统差异 | 部分 npm 包可能无法运行 | 原生模块、特定版本依赖 |
| 运行时约束 | Worker 执行时间限制 | 长时间任务需分片处理 |
| 存储限制 | KV/ Durable Objects 访问模式 | 数据持久化策略 |

### 解决方案建议

1. **条件加载**：使用特性检测加载不同模块
2. **轻量级替代**：替换重型依赖为边缘兼容版本
3. **任务分片**：将大型任务拆分为多个 Worker 调用
4. **数据预取**：在传统环境预处理数据，减少边缘计算负担

## Playwright 容器镜像

AgentQL 推荐的 Playwright 运行环境中使用以下容器镜像：

```yaml
playwright:
  - tier: recommended
    alias: playwright-latest
    image: mcr.microsoft.com/playwright:v1.58.2-noble
    uri: mcr.microsoft.com/playwright:v1.58.2-noble@sha256:65cefd09a5e943921ecd3a6e5414c603db2eb161e9eb48f2e2ccc63486dc7dc0
    runtime_version: "1.58.2"
    base_os: Ubuntu 24.04 LTS (Noble Numbat)
```

资料来源：[golden-images.yaml:1-20]()

## 常见查询模式

### 数据查询

```python
DATA_QUERY = """
{
    price_currency
    products[] {
        name
        price(integer)
    }
}
"""
```

### 元素定位

```python
SEARCH_BOX_QUERY = """
{
    search_product_box
}
"""
```

### 自然语言定位

```python
NATURAL_LANGUAGE_PROMPT = "Button to display Qwilfish page"
```

资料来源：[examples/python/first_steps/main.py:20-40]()

## 社区反馈与已知问题

### Issue #128：AgentQL (JS) x Cloudflare's Browser Rendering

这是社区中关于此集成的主要讨论话题。核心问题是边缘环境与标准 Node.js 环境的差异导致部分功能不可用。

**关键反馈点：**

- Cloudflare Browser Rendering 支持 Playwright
- Edge 环境对某些 Node.js API 有特殊限制
- 需要测试和验证具体功能的兼容性

### 问题排查清单

- [ ] 验证 Playwright 版本兼容性
- [ ] 检查全局对象使用情况
- [ ] 测试原生模块依赖
- [ ] 评估执行时间限制
- [ ] 确认数据存储方案

## 相关资源

| 资源类型 | 链接 |
|----------|------|
| Cloudflare Browser Rendering 文档 | [Cloudflare 官方文档](https://developers.cloudflare.com/browser-rendering) |
| Playwright 集成指南 | [AgentQL Playwright 文档](https://docs.agentql.com/integrations) |
| JavaScript SDK 安装 | [JS SDK 安装指南](https://docs.agentql.com/javascript-sdk/installation) |
| 社区讨论 | [GitHub Issue #128](https://github.com/tinyfish-io/agentql/issues/128) |

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：tinyfish-io/agentql

摘要：发现 8 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：Dependency Dashboard。

## 1. 安装坑 · 来源证据：Dependency Dashboard

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Dependency Dashboard
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_761b694cc0e94100b46ba5683041137b | https://github.com/tinyfish-io/agentql/issues/114 | 来源类型 github_issue 暴露的待验证使用条件。

## 2. 安装坑 · 来源证据：Starlog published a deep-dive on tinyfish-io/agentql

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Starlog published a deep-dive on tinyfish-io/agentql
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_55a8aa1466634fb39e0b679f753270ec | https://github.com/tinyfish-io/agentql/issues/148 | 来源类型 github_issue 暴露的待验证使用条件。

## 3. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:760722197 | https://github.com/tinyfish-io/agentql | README/documentation is current enough for a first validation pass.

## 4. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:760722197 | https://github.com/tinyfish-io/agentql | last_activity_observed missing

## 5. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:760722197 | https://github.com/tinyfish-io/agentql | no_demo; severity=medium

## 6. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:760722197 | https://github.com/tinyfish-io/agentql | no_demo; severity=medium

## 7. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:760722197 | https://github.com/tinyfish-io/agentql | issue_or_pr_quality=unknown

## 8. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:760722197 | https://github.com/tinyfish-io/agentql | release_recency=unknown

<!-- canonical_name: tinyfish-io/agentql; human_manual_source: deepwiki_human_wiki -->
