安装

要安装 Firecrawl Python SDK,可以使用 pip:

Python
pip install firecrawl-py

使用

  1. firecrawl.dev 获取一个 API 密钥
  2. 将 API 密钥设置为名为 FIRECRAWL_API_KEY 的环境变量,或者将其作为参数传递给 FirecrawlApp 类。

以下是一个如何使用 SDK 的示例:

Python
from firecrawl import FirecrawlApp

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

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

# 爬取一个网站:
crawl_status = app.crawl_url(
  'https://firecrawl.dev',
  params={
    'limit': 100,
    'scrapeOptions': {'formats': ['markdown', 'html']}
  }
)
print(crawl_status)

抓取 URL

要抓取单个 URL,请使用 scrape_url 方法。它接受 URL 作为参数,并返回抓取到的数据作为字典。

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

爬取网站

要爬取网站,请使用 crawl_url 方法。它接受起始 URL 和可选参数作为参数。params 参数允许你指定爬取作业的其他选项,例如要爬取的最大页面数、允许的域和输出格式。

Python
crawl_status = app.crawl_url(
  'https://firecrawl.dev',
  params={
    'limit': 100,
    'scrapeOptions': {'formats': ['markdown', 'html']}
  },
  poll_interval=30
)
print(crawl_status)

异步爬取

要异步爬取网站,请使用 crawl_url_async 方法。它返回爬取作业的 ID,你可以用它来检查爬取作业的状态。它接受起始 URL 和可选参数作为参数。params 参数允许你指定爬取作业的其他选项,例如要爬取的最大页面数、允许的域和输出格式。

Python
crawl_status = app.async_crawl_url(
  'https://firecrawl.dev',
  params={
    'limit': 100,
    'scrapeOptions': {'formats': ['markdown', 'html']}
  }
)
print(crawl_status)

检查爬取状态

要检查爬取作业的状态,请使用 check_crawl_status 方法。它接受作业 ID 作为参数,并返回爬取作业的当前状态。

Python
crawl_status = app.check_crawl_status("<crawl_id>")
print(crawl_status)

取消爬取

要取消异步爬取作业,请使用 cancel_crawl 方法。它接受异步爬取作业的作业 ID 作为参数,并返回取消状态。

Python
cancel_crawl = app.cancel_crawl(id)
print(cancel_crawl)

绘制网站图

使用 map_url 生成网站的 URL 列表。params 参数允许你自定义绘图过程,包括排除子域或利用站点地图的选项。

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

使用 WebSockets 爬取网站

要使用 WebSockets 爬取网站,请使用 crawl_url_and_watch 方法。它接受起始 URL 和可选参数作为参数。params 参数允许你指定爬取作业的其他选项,例如要爬取的最大页面数、允许的域和输出格式。

Python
# 在一个异步函数中...
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()

错误处理

SDK 处理 Firecrawl API 返回的错误并抛出适当的异常。如果请求过程中发生错误,将会抛出带有描述性错误消息的异常。