Firecrawl 提供多种代理类型,帮助你在面对不同强度的反爬虫措施时抓取网站。可以通过 proxy 参数指定代理类型。

代理类型

Firecrawl 支持三种代理类型:
  • basic:适用于无反爬或仅有基础反爬的网站。速度快,通常可行。
  • stealth:适用于有高级反爬的网站的隐身代理。速度较慢,但在某些站点更可靠。
  • auto:若 basic 代理失败,Firecrawl 会自动使用隐身代理重试抓取。若隐身重试成功,该次抓取计费 5 点额度;若首次使用 basic 即成功,则仅收取常规费用。
如果未指定代理,Firecrawl 默认使用 auto。

使用 stealth 模式

在抓取具备高级反机器人保护的网站时,可以使用 stealth 代理模式来提高成功率。
from firecrawl import Firecrawl

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

# Choose proxy strategy: 'basic' | 'stealth' | 'auto'
doc = firecrawl.scrape('https://example.com', formats=['markdown'], proxy='auto')

print(doc.warning or 'ok')
注意: 使用 stealth 代理时,每次请求消耗 5 个积分。

将 Stealth 用作重试机制

一种常见做法是先使用默认代理设置进行抓取;如果在响应的 metadata.statusCode 字段中遇到特定错误状态码(401、403 或 500),则改用 stealth 模式重试。这些状态码可能表明网站正在拦截你的请求。
# pip install firecrawl-py

from firecrawl import Firecrawl

firecrawl = Firecrawl(api_key="YOUR_API_KEY")

# First try with basic proxy
try:
    content = firecrawl.scrape("https://example.com")
    
    # Check if we got an error status code
    status_code = content.get("metadata", {}).get("statusCode")
    if status_code in [401, 403, 500]:
        print(f"Got status code {status_code}, retrying with stealth proxy")
        # Retry with stealth proxy
        content = firecrawl.scrape("https://example.com", proxy="stealth")
    
    print(content["markdown"])
except Exception as e:
    print(f"Error: {e}")
    # Retry with stealth proxy on exception
    try:
        content = firecrawl.scrape("https://example.com", proxy="stealth")
        print(content["markdown"])
    except Exception as e:
        print(f"Stealth proxy also failed: {e}")
这种方法可以让你仅在必要时启用 stealth 模式,从而更高效地使用额度。