> ## Documentation Index
> Fetch the complete documentation index at: https://student-213fb9fc.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 批量抓取

> 批量抓取多个 URL

<div id="batch-scraping-multiple-urls">
  ## 批量抓取多个 URL
</div>

现在你可以同时批量抓取多个 URL。该方法以起始 URL 和可选参数作为入参。通过 params 参数，你可以为批量抓取任务指定其他选项，例如输出 formats。

<div id="how-it-works">
  ### 工作原理
</div>

它与 `/crawl` 端点的工作方式非常相似。你可以启动批处理并等待其完成，或先启动再自行处理完成流程。

* `batchScrape`（JS）/ `batch_scrape`（Python）：启动批处理作业并等待完成，返回结果。
* `startBatchScrape`（JS）/ `start_batch_scrape`（Python）：启动批处理作业并返回作业 ID，便于你轮询或使用 webhooks。

<div id="concurrency">
  ### 并发
</div>

默认情况下，批量抓取作业会使用你团队的全部浏览器并发上限（参见 [Rate Limits](/zh/rate-limits)）。你可以通过 `maxConcurrency` 参数为每个作业降低并发数——例如，`maxConcurrency: 50` 会将该作业限制为最多 50 个同时抓取。对于大批量作业，如果将这个值设得过低，会显著减慢处理速度，因此只有在你需要为其他并发作业预留容量时才应降低它。

<div id="usage">
  ### 使用方法
</div>

<CodeGroup>
  ```python Python theme={null}
  from firecrawl import Firecrawl

  firecrawl = Firecrawl(api_key="fc-YOUR-API-KEY")

  start = firecrawl.start_batch_scrape([
      "https://firecrawl.dev",
      "https://docs.firecrawl.dev",
  ], formats=["markdown"])  # 返回 ID

  job = firecrawl.batch_scrape([
      "https://firecrawl.dev",
      "https://docs.firecrawl.dev",
  ], formats=["markdown"], poll_interval=2, wait_timeout=120)

  print(job.status, job.completed, job.total)
  ```

  ```js Node theme={null}
  import Firecrawl from '@mendable/firecrawl-js';

  const firecrawl = new Firecrawl({ apiKey: "fc-YOUR-API-KEY" });

  // 启动批量抓取任务
  const { id } = await firecrawl.startBatchScrape([
    'https://firecrawl.dev',
    'https://docs.firecrawl.dev'
  ], {
    options: { formats: ['markdown'] },
  });

  // 等待任务完成
  const job = await firecrawl.batchScrape([
    'https://firecrawl.dev',
    'https://docs.firecrawl.dev'
  ], { options: { formats: ['markdown'] }, pollInterval: 2, timeout: 120 });

  console.log(job.status, job.completed, job.total);
  ```

  ```bash cURL theme={null}
  curl -s -X POST "https://api.firecrawl.dev/v2/batch/scrape" \
    -H "Authorization: Bearer $FIRECRAWL_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "urls": ["https://firecrawl.dev", "https://docs.firecrawl.dev"],
      "formats": ["markdown"]
    }'
  ```
</CodeGroup>

<div id="response">
  ### 响应
</div>

调用 `batchScrape`/`batch_scrape` 会在批处理完成后返回完整结果。

```json 已完成 theme={null}
{
  "status": "completed",
  "total": 36,
  "completed": 36,
  "creditsUsed": 36,
  "expiresAt": "2024-00-00T00:00:00.000Z",
  "next": "https://api.firecrawl.dev/v2/batch/scrape/123-456-789?skip=26",
  "data": [
    {
      "markdown": "[Firecrawl 文档首页！[浅色标志](https://mintlify.s3-us-west-1.amazonaws.com/firecrawl/logo/light.svg)!...",
      "html": "<!DOCTYPE html><html lang=\"en\" class=\"js-focus-visible lg:[--scroll-mt:9.5rem]\" data-js-focus-visible=\"\">...",
      "metadata": {
        "title": "使用 Groq Llama 3 构建“网站对话”功能 | Firecrawl",
        "language": "en",
        "sourceURL": "https://docs.firecrawl.dev/learn/rag-llama3",
        "description": "了解如何使用 Firecrawl、Groq Llama 3 和 LangChain 构建“与你的网站对话”的机器人。",
        "ogLocaleAlternate": [],
        "statusCode": 200
      }
    },
    ...
  ]
}
```

调用 `startBatchScrape`/`start_batch_scrape` 会返回一个作业 ID。你可以通过 `getBatchScrapeStatus`/`get_batch_scrape_status`、API 端点 `/batch/scrape/{id}`，或 webhooks 来跟踪进度。作业结果在完成后会通过 API 保留 24 小时。在此之后，你仍然可以在[活动日志](https://www.firecrawl.dev/app/logs)中查看批量抓取历史和结果。

```json theme={null}
{
  "success": true,
  "id": "123-456-789",
  "url": "https://api.firecrawl.dev/v2/batch/scrape/123-456-789"
}
```

<div id="batch-scrape-with-structured-extraction">
  ## 批量抓取并进行结构化提取
</div>

你也可以使用批量抓取端点从页面中提取结构化数据。如果你想从一组 URL 中获取相同的结构化数据，这将非常有用。

<CodeGroup>
  ```python Python theme={null}
  from firecrawl import Firecrawl

  firecrawl = Firecrawl(api_key="fc-YOUR_API_KEY")

  # 抓取多个站点：
  batch_scrape_result = firecrawl.batch_scrape(
      ['https://docs.firecrawl.dev', 'https://docs.firecrawl.dev/sdks/overview'], 
      formats=[{
          'type': 'json',
          'prompt': '提取页面的标题和描述。',
          'schema': {
              'type': 'object',
              'properties': {
                  'title': {'type': 'string'},
                  'description': {'type': 'string'}
              },
              'required': ['title', 'description']
          }
      }]
  )
  print(batch_scrape_result)

  # 或者可以使用 start 方法：
  batch_scrape_job = firecrawl.start_batch_scrape(
      ['https://docs.firecrawl.dev', 'https://docs.firecrawl.dev/sdks/overview'], 
      formats=[{
          'type': 'json',
          'prompt': '提取页面的标题和描述。',
          'schema': {
              'type': 'object',
              'properties': {
                  'title': {'type': 'string'},
                  'description': {'type': 'string'}
              },
              'required': ['title', 'description']
          }
      }]
  )
  print(batch_scrape_job)

  # 然后可使用作业 ID 查询批量抓取的状态：
  batch_scrape_status = firecrawl.get_batch_scrape_status(batch_scrape_job.id)
  print(batch_scrape_status)
  ```

  ```js Node theme={null}
  import Firecrawl, { ScrapeResponse } from '@mendable/firecrawl-js';

  const firecrawl = new Firecrawl({apiKey: "fc-YOUR_API_KEY"});

  // 定义用于提取内容的 schema
  const schema = {
    type: "object",
    properties: {
      title: { type: "string" },
      description: { type: "string" }
    },
    required: ["title", "description"]
  };

  // 抓取多个网站（同步）：
  const batchScrapeResult = await firecrawl.batchScrape(['https://docs.firecrawl.dev', 'https://docs.firecrawl.dev/sdks/overview'], { 
    formats: [
      {
        type: "json",
        prompt: "从页面提取标题和描述。"
        schema: schema
      }
    ]
  });

  // 输出本次批量抓取的所有结果：
  console.log(batchScrapeResult)

  // 或者可以使用 start 方法：
  const batchScrapeJob = await firecrawl.startBatchScrape(['https://docs.firecrawl.dev', 'https://docs.firecrawl.dev/sdks/overview'], { 
    formats: [
      {
        type: "json",
        prompt: "从页面提取标题和描述。"
        schema: schema
      }
    ]
  });
  console.log(batchScrapeJob)

  // 然后可使用作业 ID 检查批量抓取的状态：
  const batchScrapeStatus = await firecrawl.getBatchScrapeStatus(batchScrapeJob.id);
  console.log(batchScrapeStatus)
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.firecrawl.dev/v2/batch/scrape \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY' \
      -d '{
        "urls": ["https://docs.firecrawl.dev", "https://docs.firecrawl.dev/sdks/overview"],
        "formats" : [{
          "type": "json",
          "prompt": "提取页面的标题和描述。",
          "schema": {
            "type": "object",
            "properties": {
              "title": {
                "type": "string"
              },
              "description": {
                "type": "string"
              }
            },
            "required": [
              "title",
              "description"
            ]
          }
        }]
      }'
  ```
</CodeGroup>

<div id="response">
  ### 响应
</div>

`batchScrape`/`batch_scrape` 返回完整结果：

```json 已完成 theme={null}
{
  "status": "completed",
  "total": 36,
  "completed": 36,
  "creditsUsed": 36,
  "expiresAt": "2024-00-00T00:00:00.000Z",
  "next": "https://api.firecrawl.dev/v2/batch/scrape/123-456-789?skip=26",
  "data": [
    {
      "json": {
        "title": "使用 Groq Llama 3 打造“网站聊天”功能 | Firecrawl",
        "description": "了解如何结合使用 Firecrawl、Groq Llama 3 和 Langchain，构建一个可与您网站对话的聊天机器人。"
      }
    },
    ...
  ]
}
```

`startBatchScrape`/`start_batch_scrape` 返回任务 ID：

```json theme={null}
{
  "success": true,
  "id": "123-456-789",
  "url": "https://api.firecrawl.dev/v2/batch/scrape/123-456-789"
}
```

<div id="batch-scrape-with-webhooks">
  ## 使用 Webhook 进行批量抓取
</div>

你可以配置 Webhook，在批次中的每个 URL 被抓取时接收实时通知。这样你可以立即处理结果，而无需等待整个批次完成。

```bash cURL theme={null}
curl -X POST https://api.firecrawl.dev/v2/batch/scrape \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -d '{
      "urls": [
        "https://example.com/page1",
        "https://example.com/page2",
        "https://example.com/page3"
      ],
      "webhook": {
        "url": "https://your-domain.com/webhook",
        "metadata": {
          "any_key": "any_value"
        },
        "events": ["started", "page", "completed"]
      }
    }'
```

<div id="quick-reference">
  ### 快速参考
</div>

**事件类型：**

* `batch_scrape.started` - 批量抓取开始时
* `batch_scrape.page` - 每个 URL 成功抓取时
* `batch_scrape.completed` - 所有 URL 处理完成时
* `batch_scrape.failed` - 批量抓取出现错误时

**基本载荷：**

```json theme={null}
{
  "success": true,
  "type": "batch_scrape.page",
  "id": "batch-job-id",
  "data": [...], // 'page' 事件的页面数据
  "metadata": {}, // Your custom metadata
  "error": null
}
```

<div id="security-verifying-webhook-signatures">
  ### 安全性：验证 Webhook 签名
</div>

来自 Firecrawl 的每个 webhook 请求都会包含一个 `X-Firecrawl-Signature` 请求头，其中包含一个 HMAC-SHA256 签名。**务必始终验证该签名**，以确保 webhook 是真实的且未被篡改。

**工作原理：**

1. 在你账号设置中的 [Advanced 选项卡](https://www.firecrawl.dev/app/settings?tab=advanced) 获取你的 webhook secret
2. 从 `X-Firecrawl-Signature` 请求头中提取签名
3. 使用你的 secret 对原始请求体计算 HMAC-SHA256
4. 使用时间安全（timing-safe）的比较函数将其与签名请求头的值进行比较

<Warning>
  切勿在未先验证签名的情况下处理 webhook。`X-Firecrawl-Signature` 请求头中的签名格式为：`sha256=abc123def456...`
</Warning>

如需查看 JavaScript 和 Python 的完整实现示例，请参阅 [Webhook 安全文档](/zh/webhooks/security)。

<div id="full-documentation">
  ### 完整文档
</div>

有关完整的 Webhook 文档（包括详细的事件载荷、高级配置和故障排查），请参阅[Webhook 文档](/zh/webhooks/overview)。
