林逍遥 AI林逍遥 AI
登录
Web搜索抓取

Web 搜索 & 抓取:构建联网 AI

·6 分钟阅读

Claude API 提供了两个内置的服务端工具:Web Search(搜索互联网)和 Web Fetch(抓取网页内容)。通过它们,你的应用可以让 Claude 实时搜索信息并提取结构化数据,无需自己集成搜索引擎 API。

你将学到什么

  • Web Search 和 Web Fetch 工具的使用方式
  • 如何在 API 中启用和配置
  • 搜索 + 分析的自动化工作流
  • 费用和限制

Web Search 工具

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=4096,
    tools=[{"type": "web_search_20260209"}],
    messages=[{"role": "user", "content": "搜索 React 19 的最新特性"}]
)

Claude 会自动构造搜索查询,获取结果后整合回答。

费用: $10 / 1000 次搜索 + 正常的 token 费用

Web Fetch 工具

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=4096,
    tools=[{"type": "web_fetch_20260209"}],
    messages=[{
        "role": "user",
        "content": "请抓取 https://example.com/api-docs 的内容,提取所有 API 端点"
    }]
)

费用: 无额外费用,只计 token 成本

搜索 + 抓取组合

同时启用两个工���,Claude 可以先搜索再深入阅读:

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=8192,
    tools=[
        {"type": "web_search_20260209"},
        {"type": "web_fetch_20260209"},
    ],
    messages=[{
        "role": "user",
        "content": "搜索 2026 年最好的 Python Web 框架,找到对比文章后提取各框架的优缺点"
    }]
)

实际应用:竞品监控

def monitor_competitor(competitor_name: str):
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=4096,
        tools=[{"type": "web_search_20260209"}],
        system="你是竞品分析师。搜索竞品最新动态,用结构化格式报告。",
        messages=[{
            "role": "user",
            "content": f"搜索 {competitor_name} 最近一个月的产品更新、融资新闻和市场动态"
        }],
        output_config={
            "format": {
                "type": "json_schema",
                "schema": {
                    "type": "object",
                    "properties": {
                        "product_updates": {"type": "array", "items": {"type": "string"}},
                        "funding_news": {"type": "array", "items": {"type": "string"}},
                        "market_moves": {"type": "array", "items": {"type": "string"}}
                    },
                    "required": ["product_updates", "funding_news", "market_moves"],
                    "additionalProperties": False
                }
            }
        }
    )
    return response.content[0].text

Tip: 结合结构化输出,可以把搜索结果直接转换为 JSON 存入数据库。

限制和注意事项

  • Web Search 每次可能执行多次搜索查询
  • 某些网站可能屏蔽爬虫
  • 搜索结果的时效性取决于搜索引擎索引
  • 大量使用时注意成本控制

实战练习

Tip: 构建一个简单的搜索分析工具。

  1. 用 Web Search 搜索你所在行业的最新新闻,用结构化输出提取
  2. 用 Web Fetch 抓取一个技术文档页面,让 Claude 整理为中文摘要
  3. 结合两者构建一个「每日行业简报」自动生成器

关键要点

Note: 本文核心总结

  • Web Search($10/千次)和 Web Fetch(免费)是 Claude 内置服务端工具
  • 直接在 tools 数组中声明即可使用,无需自己实现
  • 搜索 + 抓取 + 结构化输出 = 强大的信息采集管道

延伸阅读

二维码
微信公众号:lingxiaoyao

关注公众号,获取最新 AI 教程和课程更新

加载评论中...