> ## Documentation Index
> Fetch the complete documentation index at: https://firecrawl.web3doc.top/llms.txt
> Use this file to discover all available pages before exploring further.

# 欢迎使用 V1

> Firecrawl 允许您将整个网站转换为 LLM 准备的 Markdown

Firecrawl V1 来了！我们引入了更可靠且对开发者友好的 API。

以下是新增功能：

* `/scrape` 的输出格式。选择您希望输出的格式。
* 新的 [`/map` 端点](/features/map) 用于获取网页的大部分 URL。
* `/crawl/{id}` 状态的开发者友好 API。
* 所有计划的速率限制提高了一倍。
* [Go SDK](/sdks/go) 和 [Rust SDK](/sdks/rust)
* 团队支持
* 仪表板中的 API 密钥管理。
* `onlyMainContent` 现在默认为 `true`。
* `/crawl` webhook 和 websocket 支持。

## 抓取格式

您可以选择所需的输出格式。您可以指定多个输出格式。支持的格式有：

* Markdown (markdown)
* HTML (html)
* 原始 HTML (rawHtml)（无修改）
* 截图 (screenshot 或 screenshot\@fullPage)
* 链接 (links)
* 提取 (extract) - 结构化输出

输出键将匹配您选择的格式。

<CodeGroup>
  {' '}

  ```python Python theme={null}
  from firecrawl import FirecrawlApp

  app = FirecrawlApp(api_key="fc-YOUR_API_KEY")

  # 抓取一个网站:
  scrape_result = app.scrape_url('firecrawl.dev', params={'formats': ['markdown', 'html']})
  print(scrape_result)
  ```

  {' '}

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

  const app = new FirecrawlApp({apiKey: "fc-YOUR_API_KEY"});

  // 抓取一个网站：
  const scrapeResult = await app.scrapeUrl('firecrawl.dev', { formats: ['markdown', 'html'] }) as ScrapeResponse;

  if (!scrapeResult.success) {
    throw new Error(`抓取失败: ${scrapeResult.error}`)
  }

  console.log(scrapeResult)
  ```

  {' '}

  ```go Go theme={null}
  import (
  	"fmt"
  	"log"

  	"github.com/mendableai/firecrawl-go"
  )

  func main() {
  	// 使用你的API密钥初始化FirecrawlApp
  	apiKey := "fc-YOUR_API_KEY"
  	apiUrl := "https://api.firecrawl.dev"
  	version := "v1"

  	app, err := firecrawl.NewFirecrawlApp(apiKey, apiUrl, version)
  	if err != nil {
  		log.Fatalf("无法初始化FirecrawlApp: %v", err)
  	}

  	// 抓取一个网站
  	scrapeResult, err := app.ScrapeUrl("https://firecrawl.dev", map[string]any{
  		"formats": []string{"markdown", "html"},
  	})
  	if err != nil {
  		log.Fatalf("无法抓取URL: %v", err)
  	}

  	fmt.Println(scrapeResult)
  }
  ```

  {' '}

  ```rust Rust theme={null}
  使用 firecrawl::{FirecrawlApp, scrape::{ScrapeOptions, ScrapeFormats}};

  #[tokio::main]
  async fn main() {
      // 使用 API 密钥初始化 FirecrawlApp
      let app = FirecrawlApp::new("fc-YOUR_API_KEY").expect("无法初始化 FirecrawlApp");

      let options = ScrapeOptions {
          formats: vec![ScrapeFormats::Markdown, ScrapeFormats::HTML].into(),
          ..Default::default()
      };

      let scrape_result = app.scrape_url("https://firecrawl.dev", options).await;

      match scrape_result {
          Ok(data) => println!("抓取结果:
  {}", data.markdown.unwrap()),
          Err(e) => eprintln!("地图失败: {}", e),
      }
  }
  ```

  {' '}

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

### 响应

SDK 将直接返回数据对象。cURL 将如下所示精确返回有效负载。

```json theme={null}
{
  "success": true,
  "data" : {
    "markdown": "Launch Week I来了！[查看我们的第二天发布🚀](https://www.firecrawl.dev/blog/launch-week-i-day-2-doubled-rate-limits)[💥免费获得两个月...",
    "html": "<!DOCTYPE html><html lang=\"zh\" class=\"light\" style=\"color-scheme: light;\"><body class=\"__variable_36bd41 __variable_d7dc5d font-inter ...",
    "metadata": {
      "title": "首页 - Firecrawl",
      "description": "Firecrawl抓取并将任何网站转换为干净的Markdown。",
      "language": "zh",
      "keywords": "Firecrawl,Markdown,Data,Mendable,Langchain",
      "robots": "follow, index",
      "ogTitle": "Firecrawl",
      "ogDescription": "将任何网站转换为LLM就绪数据。",
      "ogUrl": "https://www.firecrawl.dev/",
      "ogImage": "https://www.firecrawl.dev/og.png?123",
      "ogLocaleAlternate": [],
      "ogSiteName": "Firecrawl",
      "sourceURL": "https://firecrawl.dev",
      "statusCode": 200
    }
  }
}
```

## 介绍 /map（Alpha）

从单个 URL 到整个网站的映射的最简单方法。

### 使用方式

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

  app = FirecrawlApp(api_key="fc-YOUR_API_KEY")

  # 映射一个网站:
  map_result = app.map_url('https://firecrawl.dev')
  print(map_result)
  ```

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

  const app = new FirecrawlApp({apiKey: "fc-YOUR_API_KEY"});

  const mapResult = await app.mapUrl('https://firecrawl.dev') as MapResponse;

  if (!mapResult.success) {
      throw new Error(`Failed to map: ${mapResult.error}`)
  }

  console.log(mapResult)
  ```

  ```go Go theme={null}
  import (
  	"fmt"
  	"log"

  	"github.com/mendableai/firecrawl-go"
  )

  func main() {
  	// 使用你的API密钥初始化FirecrawlApp
  	apiKey := "fc-YOUR_API_KEY"
  	apiUrl := "https://api.firecrawl.dev"
  	version := "v1"

  	app, err := firecrawl.NewFirecrawlApp(apiKey, apiUrl, version)
  	if err != nil {
  		log.Fatalf("无法初始化FirecrawlApp: %v", err)
  	}

  	// 映射一个网站
  	mapResult, err := app.MapUrl("https://firecrawl.dev", nil)
  	if err != nil {
  		log.Fatalf("无法映射URL: %v", err)
  	}

  	fmt.Println(mapResult)
  }
  ```

  ```rust Rust theme={null}
  use firecrawl::FirecrawlApp;

  #[tokio::main]
  async fn main() {
      // 使用API密钥初始化FirecrawlApp
      let app = FirecrawlApp::new("fc-YOUR_API_KEY").expect("Failed to initialize FirecrawlApp");

      let map_result = app.map_url("https://firecrawl.dev", None).await;

      match map_result {
          Ok(data) => println!("Mapped URLs: {:#?}", data),
          Err(e) => eprintln!("Map failed: {}", e),
      }
  }
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.firecrawl.dev/v1/map \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY' \
      -d '{
        "url": "https://firecrawl.dev"
      }'
  ```
</CodeGroup>

### 响应

SDK 将直接返回数据对象。cURL 将如下所示精确返回有效负载。

```json theme={null}
{
  "status": "success",
  "links": [
    "https://firecrawl.dev",
    "https://www.firecrawl.dev/pricing",
    "https://www.firecrawl.dev/blog",
    "https://www.firecrawl.dev/playground",
    "https://www.firecrawl.dev/smart-crawl",
    ...
  ]
}
```

## WebSockets

要使用 WebSockets 抓取网站，请使用“抓取 URL 并监视”方法。

<CodeGroup>
  ```python Python theme={null}
  # 在一个异步函数中...
  nest_asyncio.apply()

  # 定义事件处理程序
  def on_document(detail):
      print("DOC", detail)

  def on_error(detail):
      print("ERR", detail['error'])

  def on_done(detail):
      print("DONE", detail['status'])

  # 启动爬取和监视过程的函数
  async def start_crawl_and_watch():
      # 初始化爬取任务并获取监视器
      watcher = app.crawl_url_and_watch('firecrawl.dev', { 'excludePaths': ['blog/*'], 'limit': 5 })

      # 添加事件监听器
      watcher.add_event_listener("document", on_document)
      watcher.add_event_listener("error", on_error)
      watcher.add_event_listener("done", on_done)

      # 启动监视器
      await watcher.connect()

  # 运行事件循环
  await start_crawl_and_watch()
  ```

  ```js Node theme={null}
  const watch = await app.crawlUrlAndWatch('mendable.ai', { excludePaths: ['blog/*'], limit: 5});

  watch.addEventListener("document", doc => {
    console.log("DOC", doc.detail);
  });

  watch.addEventListener("error", err => {
    console.error("ERR", err.detail.error);
  });

  watch.addEventListener("done", state => {
    console.log("DONE", state.detail.status);
  });
  ```
</CodeGroup>

## 提取格式

LLM 提取现在在 v1 中以 `extract` 格式提供。要从页面中提取结构化数据，您可以传递一个模式到端点，或者只提供一个提示。

<CodeGroup>
  ```python Python theme={null}
  from firecrawl import FirecrawlApp
  from pydantic import BaseModel, Field

  # 使用你的API密钥初始化FirecrawlApp
  app = FirecrawlApp(api_key='your_api_key')

  class ExtractSchema(BaseModel):
      company_mission: str
      supports_sso: bool
      is_open_source: bool
      is_in_yc: bool

  data = app.scrape_url('https://docs.firecrawl.dev/', {
      'formats': ['json'],
      'jsonOptions': {
          'schema': ExtractSchema.model_json_schema(),
      }
  })
  print(data["json"])
  ```

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

  const app = new FirecrawlApp({
    apiKey: 'fc-YOUR_API_KEY',
  });

  // 定义用于提取内容的架构
  const schema = z.object({
    company_mission: z.string(),
    supports_sso: z.boolean(),
    is_open_source: z.boolean(),
    is_in_yc: z.boolean(),
  });

  const scrapeResult = await app.scrapeUrl('https://docs.firecrawl.dev/', {
    formats: ['json'],
    jsonOptions: { schema: schema },
  });

  if (!scrapeResult.success) {
    throw new Error(`抓取失败: ${scrapeResult.error}`);
  }

  console.log(scrapeResult.extract);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.firecrawl.dev/v1/scrape \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY' \
      -d '{
        "url": "https://docs.firecrawl.dev/",
        "formats": ["json"],
        "jsonOptions": {
          "schema": {
            "type": "object",
            "properties": {
              "company_mission": {
                        "type": "string"
              },
              "supports_sso": {
                        "type": "boolean"
              },
              "is_open_source": {
                        "type": "boolean"
              },
              "is_in_yc": {
                        "type": "boolean"
              }
            },
            "required": [
              "company_mission",
              "supports_sso",
              "is_open_source",
              "is_in_yc"
            ]
          }
        }
      }'
  ```
</CodeGroup>

输出：

```json JSON theme={null}
{
    "success": true,
    "data": {
      "json": {
        "company_mission": "训练一个安全的人工智能，利用您的技术资源回答客户和员工的问题，这样您的团队就不必这样做了",
        "supports_sso": true,
        "is_open_source": false,
        "is_in_yc": true
      },
      "metadata": {
        "title": "Mendable",
        "description": "Mendable让您轻松构建AI聊天应用。摄取、定制，然后只需一行代码即可在您想要的任何地方部署。由SideGuide提供支持",
        "robots": "follow, index",
        "ogTitle": "Mendable",
        "ogDescription": "Mendable让您轻松构建AI聊天应用。摄取、定制，然后只需一行代码即可在您想要的任何地方部署。由SideGuide提供支持",
        "ogUrl": "https://docs.firecrawl.dev/",
        "ogImage": "https://docs.firecrawl.dev/mendable_new_og1.png",
        "ogLocaleAlternate": [],
        "ogSiteName": "Mendable",
        "sourceURL": "https://docs.firecrawl.dev/"
      },
    }
}
```

### 无模式提取（新增）\`\`\`md

现在，您可以通过仅向端点传递一个`prompt`来提取数据而无需模式。llm将选择数据的结构。

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.firecrawl.dev/v1/scrape \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY' \
      -d '{
        "url": "https://docs.firecrawl.dev/",
        "formats": ["json"],
        "jsonOptions": {
          "prompt": "从页面中提取公司使命。"
        }
      }'
  ```
</CodeGroup>

输出：

```json JSON theme={null}
{
    "success": true,
    "data": {
      "json": {
        "company_mission": "训练一个安全的人工智能，使用您的技术资源回答客户和员工的问题，以便您的团队不必这样做",
      },
      "metadata": {
        "title": "Mendable",
        "description": "Mendable 允许您轻松构建 AI 聊天应用程序。摄取、自定义，然后只需一行代码即可在您想要的任何位置部署。由 SideGuide 提供支持",
        "robots": "follow, index",
        "ogTitle": "Mendable",
        "ogDescription": "Mendable 允许您轻松构建 AI 聊天应用程序。摄取、自定义，然后只需一行代码即可在您想要的任何位置部署。由 SideGuide 提供支持",
        "ogUrl": "https://docs.firecrawl.dev/",
        "ogImage": "https://docs.firecrawl.dev/mendable_new_og1.png",
        "ogLocaleAlternate": [],
        "ogSiteName": "Mendable",
        "sourceURL": "https://docs.firecrawl.dev/"
      },
    }
}
```

## 新的爬虫Webhook

现在，您可以向`/crawl`端点传递一个`webhook`参数。这将在开始、更新和完成爬取时向您指定的URL发送POST请求。

现在，每次爬取页面都会触发webhook，而不仅仅是在最后返回整个结果时。

```bash cURL theme={null}
curl -X POST https://api.firecrawl.dev/v1/crawl \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -d '{
      "url": "https://docs.firecrawl.dev",
      "limit": 100,
      "webhook": "https://example.com/webhook"
    }'
```

### Webhook事件

现在有4种类型的事件：

* `crawl.started` - 当爬虫开始时触发。
* `crawl.page` - 为每个爬取的页面触发。
* `crawl.completed` - 当爬虫完成时触发，以通知您它已经完成。
* `crawl.failed` - 当爬虫失败时触发。

### Webhook响应

* `success` - 如果webhook成功爬取了页面。
* `type` - 发生的事件类型。
* `id` - 爬虫的ID。
* `data` - 抓取的数据（数组）。这只有在`crawl.page`事件中才会非空，如果页面成功抓取则包含1个项目。响应与`/scrape`端点的相同。
* `error` - 如果webhook失败，这将包含错误信息。

## 从V0迁移

> ⚠️ **弃用通知**：V0端点将在2025年4月1日弃用。请在此之前迁移到V1端点以确保服务不中断。

## /scrape端点

更新后的`/scrape`端点已重新设计，以提高可靠性和易用性。新的`/scrape`请求体结构如下：

```json theme={null}
{
  "url": "<string>",
  "formats": ["markdown", "html", "rawHtml", "links", "screenshot", "json"],
  "includeTags": ["<string>"],
  "excludeTags": ["<string>"],
  "headers": { "<key>": "<value>" },
  "waitFor": 123,
  "timeout": 123
}
```

### 格式

现在，您可以选择希望输出的格式。您可以指定多个输出格式。支持的格式包括：

* Markdown (markdown)
* HTML (html)
* Raw HTML (rawHtml)（无修改）
* 截图 (screenshot或screenshot\@fullPage)
* 链接 (links)
* JSON (json)

默认情况下，输出将仅包括Markdown格式。

### 新请求体的详细信息

下表概述了V1中`/scrape`端点请求体参数的变化。

| 参数                                                               | 变化     | 描述                                                     |
| ---------------------------------------------------------------- | ------ | ------------------------------------------------------ |
| `onlyIncludeTags`                                                | 移动并重命名 | 移至根级别。并重命名为`includeTags`。                              |
| `removeTags`                                                     | 移动并重命名 | 移至根级别。并重命名为`excludeTags`。                              |
| `onlyMainContent`                                                | 移动     | 移至根级别。默认值为`true`。                                      |
| `waitFor`                                                        | 移动     | 移至根级别。                                                 |
| `headers`                                                        | 移动     | 移至根级别。                                                 |
| `parsePDF`                                                       | 移动     | 移至根级别。                                                 |
| `extractorOptions`                                               | 无变化    |                                                        |
| `timeout`                                                        | 无变化    |                                                        |
| `pageOptions`                                                    | 移除     | 不需要`pageOptions`参数。抓取选项已移至根级别。                         |
| `replaceAllPathsWithAbsolutePaths`                               | 移除     | `replaceAllPathsWithAbsolutePaths`不再需要。所有路径现在都默认为绝对路径。 |
| `includeHtml`                                                    | 移除     | 添加`"html"`到`formats`中。                                 |
| `includeRawHtml`                                                 | 移除     | 添加`"rawHtml"`到`formats`中。                              |
| `screenshot`                                                     | 移除     | 添加`"screenshot"`到`formats`中。                           |
| `fullPageScreenshot`                                             | 移除     | 添加`"screenshot@fullPage"`到`formats`中。                  |
| `extractorOptions`                                               | 移除     | 使用`"extract"`格式并带有`extract`对象。                         |
| \`\`\`新的 `extract` 格式在 [llm-extract](/features/extract) 部分中有所描述。 |        |                                                        |

## /crawl 端点

我们还更新了 V1 版本的 `/crawl` 端点。请查看下面改进的请求体：

```json theme={null}
{
  "url": "<string>",
  "excludePaths": ["<string>"],
  "includePaths": ["<string>"],
  "maxDepth": 2,
  "ignoreSitemap": true,
  "limit": 10,
  "allowBackwardLinks": true,
  "allowExternalLinks": true,
  "scrapeOptions": {
    // 与 /scrape 相同的选项
    "formats": ["markdown", "html", "rawHtml", "screenshot", "links"],
    "headers": { "<key>": "<value>" },
    "includeTags": ["<string>"],
    "excludeTags": ["<string>"],
    "onlyMainContent": true,
    "waitFor": 123
  }
}
```

### 关于新请求体的详细信息

下表概述了 V1 版本 `/crawl` 端点的请求体参数变化。

| 参数                      | 变更     | 描述                                    |
| ----------------------- | ------ | ------------------------------------- |
| `pageOptions`           | 重命名    | 重命名为 `scrapeOptions`。                 |
| `includes`              | 移动并重命名 | 移动到根级别。重命名为 `includePaths`。           |
| `excludes`              | 移动并重命名 | 移动到根级别。重命名为 `excludePaths`。           |
| `allowBackwardCrawling` | 移动并重命名 | 移动到根级别。重命名为 `allowBackwardLinks`。     |
| `allowExternalLinks`    | 移动     | 移动到根级别。                               |
| `maxDepth`              | 移动     | 移动到根级别。                               |
| `ignoreSitemap`         | 移动     | 移动到根级别。                               |
| `limit`                 | 移动     | 移动到根级别。                               |
| `crawlerOptions`        | 移除     | 不需要 `crawlerOptions` 参数。抓取选项已经移动到根级别。 |
| `timeout`               | 移除     | 使用 `scrapeOptions` 中的 `timeout` 代替。   |
