---
title: 網頁擷取工具
url: https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool
description: 從特定 URL 擷取並讀取內容，以即時網頁內容擴充 Claude 的上下文。
---

<Note>
  若要了解「zero data retention」（零資料保留），即 ZDR 如何適用於此功能，請參閱 [API 與資料保留](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention)。
</Note>

網頁擷取工具（web fetch tool）讓 Claude 能夠從指定的網頁和 PDF 文件中擷取完整內容。

最新的網頁擷取工具版本（`web_fetch_20260318`）支援 **「dynamic filtering」（動態篩選）**：Claude 可以撰寫並執行程式碼，在擷取的內容進入「context window」（上下文視窗）之前先進行篩選，只保留相關資訊並捨棄其餘部分。這能在維持回應品質的同時減少 token 消耗。動態篩選適用於 Claude 4.6 及更新的模型，以及 [Claude Mythos Preview](https://anthropic.com/glasswing)。`web_fetch_20260318` 也新增了適用於代理式工作流程的[回應納入](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool#response-inclusion)控制。先前的版本（支援動態篩選與[快取略過](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool#cache-bypass)的 `web_fetch_20260309`、僅支援動態篩選的 `web_fetch_20260209`，以及提供基本擷取功能的 `web_fetch_20250910`）仍可繼續使用。

網頁擷取（無論是否使用動態過濾）可在 Claude API、[Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws) 以及 [Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) 上使用。在 Microsoft Foundry 上，[託管於 Azure](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure) 的部署僅支援基本網頁擷取工具（`web_fetch_20250910`，不含動態過濾）。託管於 Anthropic 的部署支援所有版本。網頁擷取目前無法在 Amazon Bedrock 或 Google Cloud 上使用。

<Note>
  對於 [Claude Mythos Preview](https://anthropic.com/glasswing)，網頁擷取可在 Claude API 和 Microsoft Foundry 上使用。目前 Mythos Preview 在 Amazon Bedrock 或 Google Cloud 上無法使用網頁擷取。
</Note>

<Note>
  請使用[意見回饋表單](https://forms.gle/NhWcgmkcvPCMmPE86)針對模型回應品質、API 本身或文件品質提供意見回饋。
</Note>

關於零資料保留（Zero Data Retention）資格以及 `allowed_callers` 的替代方案，請參閱[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#zdr-and-allowed-callers)。

<Warning>
  在 Claude 會同時處理不受信任的輸入與敏感資料的環境中啟用網頁擷取工具，會帶來資料外洩風險。請僅在受信任的環境中或處理非敏感資料時使用此工具。

  為了將外洩風險降到最低，Claude 無法擷取僅出現在其自身輸出中的 URL。Claude 只能擷取先前已出現在對話中的 URL：使用者訊息中的 URL、用戶端工具結果中的 URL（即使該結果回顯了 Claude 所產生的文字），以及先前網頁搜尋或網頁擷取結果中的 URL（請參閱 [URL 驗證](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool#url-validation)）。Claude 也無法擷取看似包含憑證（例如 API 金鑰或密碼）的 URL，除非該憑證出現在系統提示中或使用者訊息的文字中。

  然而，仍存在殘餘風險，您在使用此工具時應審慎考量。

  如果資料外洩是一項顧慮，請考慮：

  * 完全停用網頁擷取工具
  * 使用 `max_uses` 參數限制請求次數
  * 使用 `allowed_domains` 參數限制為已知的安全網域
</Warning>

關於模型支援，請參閱[工具參考](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference)。

## 網頁擷取的運作方式

網頁擷取是一種[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools)（server tool）：API 會在請求期間擷取內容，並將結果插入對話中。您不需要執行任何操作或回傳 `tool_result`。例外情況是當 Claude 在同一組平行工具呼叫中同時呼叫網頁擷取與您的某個用戶端工具時：API 會在該擷取執行之前以 `stop_reason: "tool_use"` 回傳回應，然後在您送回用戶端 `tool_result` 區塊時執行擷取。請參閱[在同一輪中混合使用伺服器工具與用戶端工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#mixing-server-tools-and-client-tools-in-one-turn)。

當您將網頁擷取工具加入 API 請求時：

1. Claude 會根據提示和可用的 URL 決定何時擷取內容。
2. API 從指定的 URL 擷取完整的文字內容。
3. 對於 PDF，API 會以 base64 編碼資料的形式回傳內容，並像直接附加的 PDF 文件一樣處理。
4. Claude 分析擷取的內容，並提供附有選用引用的回應。

<Note>
  網頁擷取工具目前不支援以 JavaScript 動態渲染的網站。對於需要真實瀏覽器的頁面（JavaScript 渲染、點擊或填寫表單），請考慮使用[瀏覽器使用工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/browser-use-tool)，這是一種用戶端工具，由您的應用程式驅動瀏覽器，並將頁面文字或螢幕截圖作為工具結果回傳給 Claude。
</Note>

### Claude 何時進行擷取

當請求指向特定頁面或文件時，Claude 會進行擷取：

* 對話中（或先前的工具結果中）提供了 URL
* 使用者指名特定資源（某篇文章、README、定價頁面或文件章節）但未提供 URL，且同時啟用了[網頁搜尋工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool)，讓 Claude 能先找到它（請參閱[結合搜尋與擷取](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool#combined-search-and-fetch)）

對於未提及特定頁面的一般知識或開放式問題，Claude **不會**進行擷取。「摘要這篇文章：`<url>`」會觸發擷取。「REST API 設計的最佳實務是什麼？」則會直接回答。

### 動態過濾

擷取完整的網頁和 PDF 可能會快速消耗 token，尤其是當只需要大型文件中的特定資訊時。使用 `web_fetch_20260209` 或更新版本時，Claude 可以撰寫並執行程式碼，在將擷取的內容載入上下文之前先行過濾。

這種動態過濾特別適用於：

* 從長篇文件中擷取特定章節
* 處理網頁中的結構化資料
* 從 PDF 中過濾相關資訊
* 在處理大型文件時降低 token 成本

<Note>
  動態過濾在[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)上執行，API 會自動為該請求啟用此工具。您不需要將程式碼執行工具加入 `tools` 陣列。
</Note>

若要啟用動態過濾，請使用 `web_fetch_20260209` 或任何更新版本。以下範例使用 `web_fetch_20260318`：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "Fetch the content at https://example.com/research-paper and extract the key findings."
        }
      ],
      "tools": [{
        "type": "web_fetch_20260318",
        "name": "web_fetch"
      }]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content: >-
        Fetch the content at https://example.com/research-paper
        and extract the key findings.
  tools:
    - type: web_fetch_20260318
      name: web_fetch
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Fetch the content at https://example.com/research-paper and extract the key findings.",
          }
      ],
      tools=[{"type": "web_fetch_20260318", "name": "web_fetch"}],
  )
  print(response)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content:
          "Fetch the content at https://example.com/research-paper and extract the key findings."
      }
    ],
    tools: [{ type: "web_fetch_20260318", name: "web_fetch" }]
  });

  console.log(response);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Fetch the content at https://example.com/research-paper and extract the key findings." }],
      Tools = [new ToolUnion(new WebFetchTool20260318())]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Fetch the content at https://example.com/research-paper and extract the key findings.")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfWebFetchTool20260318: &anthropic.WebFetchTool20260318Param{}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.WebFetchTool20260318;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Fetch the content at https://example.com/research-paper and extract the key findings.")
          .addTool(WebFetchTool20260318.builder().build())
          .build();

      Message response = client.messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 4096,
      messages: [
          ['role' => 'user', 'content' => 'Fetch the content at https://example.com/research-paper and extract the key findings.']
      ],
      model: 'claude-opus-5-5',
      tools: [[
          'type' => 'web_fetch_20260318',
          'name' => 'web_fetch',
      ]],
  );
  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      { role: "user", content: "Fetch the content at https://example.com/research-paper and extract the key findings." }
    ],
    tools: [{
      type: "web_fetch_20260318",
      name: "web_fetch"
    }]
  )
  puts message
  ```
</CodeGroup>

## 如何使用網頁擷取

在您的 API 請求中提供網頁擷取工具：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [
        {
          "role": "user",
          "content": "Please analyze the content at https://example.com/article"
        }
      ],
      "tools": [{
        "type": "web_fetch_20250910",
        "name": "web_fetch",
        "max_uses": 5
      }]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Please analyze the content at https://example.com/article"}' \
    --tool '{type: web_fetch_20250910, name: web_fetch, max_uses: 5}'
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[
          {
              "role": "user",
              "content": "Please analyze the content at https://example.com/article",
          }
      ],
      tools=[{"type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5}],
  )
  print(response)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: "Please analyze the content at https://example.com/article"
      }
    ],
    tools: [
      {
        type: "web_fetch_20250910",
        name: "web_fetch",
        max_uses: 5
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new() { Role = Role.User, Content = "Please analyze the content at https://example.com/article" }],
      Tools = [new ToolUnion(new WebFetchTool20250910() { MaxUses = 5 })]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Please analyze the content at https://example.com/article")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfWebFetchTool20250910: &anthropic.WebFetchTool20250910Param{
  			MaxUses: anthropic.Int(5),
  		}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.WebFetchTool20250910;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addUserMessage("Please analyze the content at https://example.com/article")
          .addTool(WebFetchTool20250910.builder()
              .maxUses(5L)
              .build())
          .build();

      Message response = client.messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 1024,
      messages: [
          ['role' => 'user', 'content' => 'Please analyze the content at https://example.com/article']
      ],
      model: 'claude-opus-5-5',
      tools: [[
          'type' => 'web_fetch_20250910',
          'name' => 'web_fetch',
          'max_uses' => 5,
      ]],
  );
  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [
      { role: "user", content: "Please analyze the content at https://example.com/article" }
    ],
    tools: [{
      type: "web_fetch_20250910",
      name: "web_fetch",
      max_uses: 5
    }]
  )
  puts message
  ```
</CodeGroup>

## 工具定義

網頁擷取工具支援以下參數：

```json JSON
{
  "type": "web_fetch_20250910",
  "name": "web_fetch",

  // Optional: Limit the number of fetches per request
  "max_uses": 10,

  // Optional: Only fetch from these domains
  "allowed_domains": ["example.com", "docs.example.com"],

  // Optional: Never fetch from these domains (cannot be combined with allowed_domains)
  "blocked_domains": ["private.example.com"],

  // Optional: Enable citations for fetched content
  "citations": {
    "enabled": true
  },

  // Optional: Maximum content length in tokens
  "max_content_tokens": 100000
}
```

較新的工具版本新增了兩個選用參數：`use_cache` 需要 `web_fetch_20260309` 或更新版本（請參閱[快取繞過](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool#cache-bypass)），而 `response_inclusion` 需要 `web_fetch_20260318` 或更新版本（請參閱[回應包含](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool#response-inclusion)）。

### 最大使用次數

`max_uses` 參數限制執行網頁擷取的次數。失敗的擷取也會計入限制。如果 Claude 嘗試的擷取次數超過允許值，`web_fetch_tool_result` 會是帶有 `max_uses_exceeded` 錯誤代碼的錯誤。目前沒有預設限制。

### 網域過濾

關於使用 `allowed_domains` 和 `blocked_domains` 進行網域過濾，請參閱[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#domain-filtering)。

在 [Claude Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview) 上，請在代理工具集的 `web_fetch` 項目中設定這些欄位，其中每個列出的網域都必須是不含路徑的純主機名稱；請參閱[限制網頁搜尋與網頁擷取的網域](https://platform.claude.com/docs/zh-TW/managed-agents/tools-web-restrictions)。

### 內容限制

`max_content_tokens` 參數限制納入上下文的內容量。如果擷取的內容超過此限制，工具會將其截斷。這有助於在擷取大型文件時控制 token 用量。此限制適用於文字內容，不適用於 PDF 等二進位內容。

<Note>
  `max_content_tokens` 參數限制為近似值。實際使用的輸入 token 數量可能會有少量差異。
</Note>

在 Claude Managed Agents 上，代理工具集的 `web_fetch` 項目也接受 `max_content_tokens`；請參閱[網頁工具設定](https://platform.claude.com/docs/zh-TW/managed-agents/tools-web-restrictions#settings)。

### 快取繞過

<Note>
  需要 `web_fetch_20260309` 或更新版本（包括 `web_fetch_20260318`）。
</Note>

`use_cache` 參數控制是否可回傳快取內容。設定 `"use_cache": false` 可繞過快取並擷取最新內容。預設值為 `true`。請僅在使用者明確要求最新內容或擷取快速變動的來源時停用快取，因為繞過快取會增加「latency」（延遲）。

```json
{
  "tools": [
    {
      "type": "web_fetch_20260309",
      "name": "web_fetch",
      "use_cache": false
    }
  ]
}
```

### 回應包含

<Note>
  需要 `web_fetch_20260318` 或更新版本。
</Note>

`response_inclusion` 參數控制當擷取結果在同一輪中被已完成的[程式碼執行](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)呼叫所使用時，擷取結果區塊在 API 回應中的呈現方式。設定 `"response_inclusion": "excluded"` 可將這些巢狀的 `server_tool_use` 與結果區塊配對從回應中完全移除，為不需要將原始頁面內容回傳給用戶端的代理式工作流程降低輸出 token 成本。預設值為 `"full"`。來自直接呼叫的結果，或來自在完成前暫停的程式碼執行呼叫的結果，一律會完整回傳，以便在下一輪中送回。

```json
{
  "tools": [
    {
      "type": "web_fetch_20260318",
      "name": "web_fetch",
      "response_inclusion": "excluded"
    }
  ]
}
```

### 引用

與一律啟用引用的網頁搜尋不同，網頁擷取的引用是選用的，且預設為停用。設定 `"citations": {"enabled": true}` 可讓 Claude 引用擷取文件中的特定段落。

<Note>
  直接向終端使用者顯示 API 輸出時，請附上原始來源的引用。如果您會修改 API 輸出，包括在向終端使用者顯示之前重新處理或將其與您自己的素材結合，請在諮詢您的法務團隊後，視情況顯示引用。
</Note>

## 回應

以下是回應結構範例：

```json Output
{
  "role": "assistant",
  "content": [
    // 1. Claude's decision to fetch
    {
      "type": "text",
      "text": "I'll fetch the content from the article to analyze it."
    },
    // 2. The fetch request
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01234567890abcdef",
      "name": "web_fetch",
      "input": {
        "url": "https://example.com/article"
      }
    },
    // 3. Fetch results
    {
      "type": "web_fetch_tool_result",
      "tool_use_id": "srvtoolu_01234567890abcdef",
      "content": {
        "type": "web_fetch_result",
        "url": "https://example.com/article",
        "content": {
          "type": "document",
          "source": {
            "type": "text",
            "media_type": "text/plain",
            "data": "Full text content of the article..."
          },
          "title": "Article Title",
          "citations": { "enabled": true }
        },
        "retrieved_at": "2025-08-25T10:30:00Z"
      }
    },
    // 4. Claude's analysis with citations (if enabled)
    {
      "text": "Based on the article, ",
      "type": "text"
    },
    {
      "text": "the main argument presented is that artificial intelligence will transform healthcare",
      "type": "text",
      "citations": [
        {
          "type": "char_location",
          "document_index": 0,
          "document_title": "Article Title",
          "start_char_index": 1234,
          "end_char_index": 1456,
          "cited_text": "Artificial intelligence is poised to revolutionize healthcare delivery..."
        }
      ]
    }
  ],
  "id": "msg_a930390d3a",
  "usage": {
    "input_tokens": 25039,
    "output_tokens": 931,
    "server_tool_use": {
      "web_fetch_requests": 1
    }
  },
  "stop_reason": "end_turn"
}
```

### 擷取結果

擷取結果包含：

* `url`：所擷取的 URL
* `content`：包含擷取內容的文件區塊
* `retrieved_at`：擷取內容時的時間戳記

<Note>
  網頁擷取工具會快取結果以提升效能並減少重複請求。回傳的內容可能不一定反映該 URL 上可用的最新版本。快取行為由系統自動管理，並可能隨時間變更，以針對不同的內容類型和使用模式進行最佳化。若要擷取最新內容，請設定 `"use_cache": false`（請參閱[快取繞過](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool#cache-bypass)）。
</Note>

對於 PDF 文件，內容會以 base64 編碼資料的形式回傳：

```json Output
{
  "type": "web_fetch_tool_result",
  "tool_use_id": "srvtoolu_02",
  "content": {
    "type": "web_fetch_result",
    "url": "https://example.com/paper.pdf",
    "content": {
      "type": "document",
      "source": {
        "type": "base64",
        "media_type": "application/pdf",
        "data": "JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmo..."
      },
      "citations": { "enabled": true }
    },
    "retrieved_at": "2025-08-25T10:30:02Z"
  }
}
```

### 錯誤

當網頁擷取工具遇到錯誤時，Claude API 會回傳 200（成功）回應，並在回應主體中表示該錯誤。Claude 會看到錯誤結果並繼續該輪對話。例如：

```json Output
{
  "type": "web_fetch_tool_result",
  "tool_use_id": "srvtoolu_a93jad",
  "content": {
    "type": "web_fetch_tool_result_error",
    "error_code": "url_not_accessible"
  }
}
```

以下是可能的錯誤代碼：

* `invalid_tool_input`：無效的工具輸入，例如格式錯誤的 URL 或非 HTTP(S) 協定
* `url_too_long`：URL 超過最大長度（250 個字元）
* `url_not_allowed`：URL 被網域過濾規則（包括您組織的設定）或 Anthropic 端的限制（例如私有位址、`robots.txt`，以及看似包含您未提供之憑證的 URL）所封鎖
* `url_not_in_prior_context`：URL 未曾出現在對話的先前內容中（請參閱 [URL 驗證](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool#url-validation)）
* `url_not_accessible`：擷取內容失敗（HTTP 錯誤）
* `too_many_requests`：超過速率限制
* `unsupported_content_type`：不支援的內容類型（僅支援文字、HTML 和 PDF）
* `max_uses_exceeded`：超過網頁擷取工具的最大使用次數
* `unavailable`：發生內部錯誤

## URL 驗證

基於安全考量，網頁擷取工具只能擷取先前曾出現在對話上下文中的 URL。這包括：

* 使用者訊息中的 URL
* 用戶端工具結果中的 URL
* 來自先前網頁搜尋或網頁擷取結果的 URL

此工具無法擷取僅出現在 Claude 自身輸出中，或僅出現在「system prompt」（系統提示）中的 URL。若要讓系統提示中的 URL 可被擷取，請同時將其包含在使用者訊息中。其他伺服器端工具的結果，例如[程式碼執行](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)、[MCP 連接器](https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector)或[工具搜尋](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool)，也不是允許的來源。用戶端工具結果即使回顯了 Claude 所產生的文字（例如會印出其輸入的指令，或引用該文字的錯誤訊息），仍屬於允許的來源。

此工具也會拒絕看似包含憑證（例如 API 金鑰或密碼）的 URL，除非該憑證出現在系統提示中或使用者訊息的文字中。僅出現在工具結果中的憑證不算數。此時會回傳 `url_not_allowed` 錯誤。若要擷取此類 URL，請將其包含在使用者訊息中。

## 結合搜尋與擷取

當網頁搜尋與網頁擷取工具同時啟用，且使用者指名特定頁面或文件但未提供 URL 時（例如「讀取 anthropics/anthropic-sdk-python 儲存庫的 README」），Claude 會使用網頁搜尋找到它，然後擷取結果。以下範例在單一請求中要求進行搜尋與分析：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "Find recent articles about quantum computing and analyze the most relevant one in detail"
        }
      ],
      "tools": [
        {
          "type": "web_search_20250305",
          "name": "web_search",
          "max_uses": 3
        },
        {
          "type": "web_fetch_20250910",
          "name": "web_fetch",
          "max_uses": 5,
          "citations": {"enabled": true}
        }
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content: >-
        Find recent articles about quantum computing
        and analyze the most relevant one in detail
  tools:
    - type: web_search_20250305
      name: web_search
      max_uses: 3
    - type: web_fetch_20250910
      name: web_fetch
      max_uses: 5
      citations:
        enabled: true
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Find recent articles about quantum computing and analyze the most relevant one in detail",
          }
      ],
      tools=[
          {"type": "web_search_20250305", "name": "web_search", "max_uses": 3},
          {
              "type": "web_fetch_20250910",
              "name": "web_fetch",
              "max_uses": 5,
              "citations": {"enabled": True},
          },
      ],
  )
  print(response)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content:
          "Find recent articles about quantum computing and analyze the most relevant one in detail"
      }
    ],
    tools: [
      { type: "web_search_20250305", name: "web_search", max_uses: 3 },
      {
        type: "web_fetch_20250910",
        name: "web_fetch",
        max_uses: 5,
        citations: { enabled: true }
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new() { Role = Role.User, Content = "Find recent articles about quantum computing and analyze the most relevant one in detail" }],
      Tools = [
          new ToolUnion(new WebSearchTool20250305() { MaxUses = 3 }),
          new ToolUnion(new WebFetchTool20250910() { MaxUses = 5, Citations = new() { Enabled = true } })
      ]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Find recent articles about quantum computing and analyze the most relevant one in detail")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfWebSearchTool20250305: &anthropic.WebSearchTool20250305Param{
  			MaxUses: anthropic.Int(3),
  		}},
  		{OfWebFetchTool20250910: &anthropic.WebFetchTool20250910Param{
  			MaxUses:   anthropic.Int(5),
  			Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},
  		}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.CitationsConfigParam;
  // ...
  import com.anthropic.models.messages.WebFetchTool20250910;
  import com.anthropic.models.messages.WebSearchTool20250305;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Find recent articles about quantum computing and analyze the most relevant one in detail")
          .addTool(WebSearchTool20250305.builder()
              .maxUses(3L)
              .build())
          .addTool(WebFetchTool20250910.builder()
              .maxUses(5L)
              .citations(CitationsConfigParam.builder().enabled(true).build())
              .build())
          .build();

      Message response = client.messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 4096,
      messages: [
          ['role' => 'user', 'content' => 'Find recent articles about quantum computing and analyze the most relevant one in detail']
      ],
      model: 'claude-opus-5-5',
      tools: [
          [
              'type' => 'web_search_20250305',
              'name' => 'web_search',
              'max_uses' => 3,
          ],
          [
              'type' => 'web_fetch_20250910',
              'name' => 'web_fetch',
              'max_uses' => 5,
              'citations' => ['enabled' => true],
          ],
      ],
  );
  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 4096,
    messages: [
      { role: "user", content: "Find recent articles about quantum computing and analyze the most relevant one in detail" }
    ],
    tools: [
      {
        type: "web_search_20250305",
        name: "web_search",
        max_uses: 3
      },
      {
        type: "web_fetch_20250910",
        name: "web_fetch",
        max_uses: 5,
        citations: { enabled: true }
      }
    ]
  )
  puts message
  ```
</CodeGroup>

在此工作流程中，Claude 會：

1. 使用網頁搜尋尋找相關文章。
2. 選擇最有希望的結果。
3. 使用網頁擷取取得完整內容。
4. 提供附有引用的詳細分析。

## 提示快取

若要跨輪次快取工具定義，請參閱[搭配提示快取的工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-use-with-prompt-caching)。

## 串流

啟用「streaming」（串流）時，擷取事件會成為串流的一部分，並在內容擷取期間暫停：

```sse Output
event: message_start
data: {"type": "message_start", "message": {"id": "msg_abc123", "type": "message"}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

// Claude's decision to fetch

event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "web_fetch"}}

// Fetch URL streamed
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"url\":\"https://example.com/article\"}"}}

// Pause while fetch executes

// Fetch results streamed
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "web_fetch_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "web_fetch_result", "url": "https://example.com/article", "content": {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "Article content..."}}}}}

// Claude's response continues...
```

## 批次請求

您可以在 [Messages Batches API](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing) 中包含網頁擷取工具。透過 Messages Batches API 進行的網頁擷取工具呼叫，其定價與一般 Messages API 請求中的呼叫相同。

## 用量與定價

Web fetch（網頁擷取）的使用除標準 token 費用外**沒有額外收費**：

```json
{
  "usage": {
    "input_tokens": 25039,
    "output_tokens": 931,
    "cache_read_input_tokens": 0,
    "cache_creation_input_tokens": 0,
    "server_tool_use": {
      "web_fetch_requests": 1
    }
  }
}
```

Web fetch 工具可在 Claude API 上使用，**無需額外費用**。您只需為成為對話上下文一部分的擷取內容支付標準 token 費用。

為防止無意間擷取會消耗過多 token 的大型內容，請使用 `max_content_tokens` 參數，根據您的使用情境與預算考量設定適當的限制。

典型內容的 token 使用量範例：

* 一般網頁（10 kB）：約 2,500 個 token
* 大型文件頁面（100 kB）：約 25,000 個 token
* 研究論文 PDF（500 kB）：約 125,000 個 token

## 後續步驟

<CardGroup>
  <Card href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool" title="程式碼執行工具" icon="code">
    在沙箱容器中執行 Python 和 bash 程式碼，以分析資料、產生檔案並反覆改進解決方案。
  </Card>

  <Card href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools" title="伺服器工具" icon="cloud">
    使用由 Anthropic 執行的工具：server\_tool\_use 區塊、pause\_turn 接續以及網域過濾。
  </Card>

  <Card href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference" title="工具參考" icon="book">
    Anthropic 提供的工具目錄，以及選用工具定義屬性的參考。
  </Card>
</CardGroup>
