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

# Python

> Firecrawl Python SDK は、Firecrawl API のラッパーで、ウェブの検索、スクレイピング、クロールを行い、クリーンな Markdown や構造化データを取得できます。

## インストール

Firecrawl の Python SDK をインストールするには、pip を使用します：

```python Python theme={null}
# pip install firecrawl

from firecrawl import Firecrawl

firecrawl = Firecrawl(
  # 開始にAPIキーは不要です — より高いrate limitsが必要な場合は追加してください:
  # api_key="fc-YOUR-API-KEY",
)
```

## 使い方

[firecrawl.dev](https://firecrawl.dev) で API キーを取得し、環境変数 `FIRECRAWL_API_KEY` に設定するか、`Firecrawl` クラスに直接渡します。

> [!NOTE]
>
> **API キーをお持ちでないですか？** `Firecrawl` はキーなしでも作成でき、キー不要の Free ティアで `scrape`、`search`、`interact` を使用できます (IP ごとにレート制限あり。詳しくは [Rate Limits](https://docs.firecrawl.dev/ja/rate-limits.md#keyless-no-api-key) を参照してください) 。それ以外のすべてのメソッドではキーが必要です。

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

firecrawl = Firecrawl(api_key="fc-YOUR_API_KEY")

# ウェブサイトをスクレイプする：
scrape_status = firecrawl.scrape(
  'https://firecrawl.dev', 
  formats=['markdown', 'html']
)
print(scrape_status)

# ウェブサイトをクロールする：
crawl_status = firecrawl.crawl(
  'https://firecrawl.dev', 
  limit=100, 
  scrape_options={
    'formats': ['markdown', 'html']
  }
)
print(crawl_status)
```

### URLのスクレイピング

`scrape` メソッドを使用して単一のURLをスクレイピングします。ページのコンテンツを、Markdown、メタデータ、およびリクエストしたその他のフォーマットを含む構造化データとして返します。

```python Python theme={null}
# ウェブサイトをスクレイピングする:
scrape_result = firecrawl.scrape('firecrawl.dev', formats=['markdown', 'html'])
print(scrape_result)
```

> [!NOTE]
>
> Python SDK は、すべてのレスポンスフィールド名を camelCase から snake\_case に変換します。たとえば、API の `ogImage`、`ogTitle`、`sourceURL` などのメタデータフィールドは、SDK のレスポンスでは `og_image`、`og_title`、`source_url` になります。

### アップロードしたファイルの解析

`parse` を使うと、ローカルファイル (`html`、`pdf`、`docx`、`xlsx` など) を `/v2/parse` に直接アップロードできます。
`parse` は `changeTracking` や、アクション、wait\_for、ロケーション、mobile、screenshot、branding などのブラウザ専用オプションには対応していません。

```python Python theme={null}
from firecrawl.v2.types import ParseOptions

parsed = firecrawl.parse(
    b"<!DOCTYPE html><html><body><h1>Python Parse</h1></body></html>",
    filename="upload.html",
    content_type="text/html",
    options=ParseOptions(formats=["markdown"]),
)

print(parsed.markdown)
```

### ウェブサイトをクロールする

ウェブサイトをクロールするには、`crawl` メソッドを使用します。開始URLと任意のオプションを引数に取ります。オプションでは、クロールするページ数の上限、許可するドメイン、出力フォーマットなど、クロールジョブの追加設定を指定できます。自動/手動のページネーションや制限については [Pagination](#pagination) を参照してください。

```python Python theme={null}
job = firecrawl.crawl(url="https://docs.firecrawl.dev", limit=5, poll_interval=1, timeout=120)
print(job)
```

### サイトマップのみクロール

`sitemap="only"` を使用して、サイトマップの URL のみをクロールします (開始 URL は常に含まれ、HTML のリンク探索は行われません) 。

```python Python theme={null}
job = firecrawl.crawl(url="https://docs.firecrawl.dev", sitemap="only", limit=25)
print(job.status, len(job.data))
```

### クロールを開始

> [!TIP]
>
> ノンブロッキングがお好みですか？下の[Async Class](#async-class)セクションをご覧ください。

`start_crawl` を使うと待たずにジョブを開始できます。ステータス確認に使えるジョブの `ID` を返します。完了までブロックして待機したい場合は `crawl` を使用してください。ページングの動作と制限は [Pagination](#pagination) を参照してください。

```python Python theme={null}
job = firecrawl.start_crawl(url="https://docs.firecrawl.dev", limit=10)
print(job)
```

### クロールのステータスを確認する

`get_crawl_status` を使用して、クロールジョブのステータスを確認します。ジョブ ID を渡すと、現在のステータスと、それまでに収集された結果を取得できます。

```python Python theme={null}
status = firecrawl.get_crawl_status("<crawl-id>")
print(status)
```

### クロールのキャンセル

クロールジョブをキャンセルするには、`cancel_crawl` メソッドを使用します。`start_crawl` が返すジョブIDを渡すと、キャンセル結果のステータスを受け取れます。

```python Python theme={null}
ok = firecrawl.cancel_crawl("<crawl-id>")
print("キャンセル済み:", ok)
```

### ウェブサイトをマッピングする

`map` を使って、ウェブサイトから URL の一覧を生成します。オプションで、サブドメインの除外やサイトマップの利用など、マッピングの挙動をカスタマイズできます。

```python Python theme={null}
res = firecrawl.map(url="https://firecrawl.dev", limit=10)
print(res)
```

### エージェントを実行する

`agent` メソッドを使用して、調査または抽出タスクをエージェントに渡します。このメソッドには、`prompt`、出力の形式を指定する任意の `schema`、実行で消費できるクレジットの上限を設定する `max_credits` を指定します。

```python Python theme={null}
from firecrawl import Firecrawl
from pydantic import BaseModel, Field
from typing import List, Optional

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

class Founder(BaseModel):
    name: str = Field(description="Full name of the founder")
    role: Optional[str] = Field(None, description="Role or position")
    background: Optional[str] = Field(None, description="Professional background")

class FoundersSchema(BaseModel):
    founders: List[Founder] = Field(description="List of founders")

result = app.agent(
    prompt="Find the founders of Firecrawl",
    schema=FoundersSchema,
    model="spark-2",
    max_credits=100
)

print(result.data)
```

エージェントの実行は非同期です。`start_agent` を使用するとジョブ ID がすぐに返され、その後 `get_agent_status` でポーリングできます。

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

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

# エージェントジョブを開始する
agent_job = app.start_agent(
    prompt="Find the founders of Firecrawl"
)

# Check the status
status = app.get_agent_status(agent_job.id)

print(status)
# Example output:
# status='completed'
# success=True
# data={ ... }
# expires_at=datetime.datetime(...)
# credits_used=15
```

`max_credits` に達した実行は、`status="failed"` と `stop_reason="credit_limit_reached"` を返します。この場合、`data` の代わりに、ベストエフォートで生成された `partial` と `partial_schema_valid` が含まれることがあります。これらの使い方や、`thread_id` を使ってスレッドを継続する方法については、[クレジット上限による停止への対処](https://docs.firecrawl.dev/ja/features/agent.md#handling-credit-limit-stops) を参照してください。

各実行では、実行トレースと出力スナップショットも記録されます。これらは `get_agent_trace` と `get_agent_snapshot` で取得できます。イベントスキーマとすべてのパラメータについては、[Agent](https://docs.firecrawl.dev/ja/features/agent.md) を参照してください。

### Alexandria データツール

[Alexandria](https://docs.firecrawl.dev/ja/features/alexandria.md) は、サードパーティのデータプロバイダーを集めた Firecrawl のカタログです。`find_tools` を使えば、プロバイダーの閲覧やツール仕様の確認を無料で行えます。ツールを実行するには、URL の代わりに `scrape(alexandria=...)` を指定します。

```python Python theme={null}
catalogue = firecrawl.find_tools(providers=["arxiv-org"], limit=2)
print(catalogue.items)

result = firecrawl.scrape(
    alexandria={
        "provider": "arxiv-org",
        "capability": "papers/search_papers",
        "options": {"query": "AI agents", "max_results": 2},
    },
)

for item in result.alexandria:
    if item.error:
        print(item.error.code, item.error.message)
    else:
        print(item.data)
```

`alexandria` には、最大 10 件の呼び出しをリストで渡すこともできます。`scrape_alexandria(calls)` は `scrape(alexandria=calls)` と同じ動作をします。`result.alexandria` の各項目には `data` または `error` が含まれ、`result.credits_cost` で合計コストを確認できます。結果が不確かな場合にリトライするには、同じリクエストに同じ `request_id` を指定して再送信してください。また、`sources=["alexandria"]` を指定して `search` を実行すると、一致するツールも `result.tools` に返されます。

### WebSockets を使ったウェブサイトのクロール

WebSockets でウェブサイトをクロールするには、`start_crawl` でジョブを開始し、`watcher` ヘルパーで購読します。ジョブ ID を指定して watcher を作成し、`start()` を呼び出す前にハンドラー (例: page、completed、failed) を登録します。

```python Python theme={null}
import asyncio
from firecrawl import AsyncFirecrawl

async def main():
    firecrawl = AsyncFirecrawl(api_key="fc-YOUR-API-KEY")

    # 最初にクロールを開始
    started = await firecrawl.start_crawl("https://firecrawl.dev", limit=5)

    # 終了ステータスまで更新（スナップショット）を監視
    async for snapshot in firecrawl.watcher(started.id, kind="crawl", poll_interval=2, timeout=120):
        if snapshot.status == "completed":
            print("完了", snapshot.status)
            for doc in snapshot.data:
                print("DOC", doc.metadata.source_url if doc.metadata else None)
        elif snapshot.status == "failed":
            print("エラー", snapshot.status)
        else:
            print("ステータス", snapshot.status, snapshot.completed, "/", snapshot.total)

asyncio.run(main())
```

### ページネーション

Firecrawl の /crawl および batch scrape の各エンドポイントは、追加のデータがある場合に `next` URL を返します。Python SDK はデフォルトで自動ページネーションを行い、すべてのドキュメントを集約します。この場合、`next` は `None` になります。自動ページネーションを無効化したり、ページネーションの動作を制御するための上限を設定することも可能です。

#### PaginationConfig

`get_crawl_status` または `get_batch_scrape_status` を呼び出す際のページネーション動作を制御するには、`PaginationConfig` を使用します。

```python Python theme={null}
from firecrawl.v2.types import PaginationConfig
```

| オプション | 型 | デフォルト | 説明 |
| - | - | - | - |
| `auto_paginate` | `bool` | `True` | `True` の場合、すべてのページを自動的に取得して結果を集約します。1 ページずつ取得するには `False` に設定します。 |
| `max_pages` | `int` | `None` | 指定したページ数を取得したら終了します (`auto_paginate=True` の場合にのみ適用されます) 。 |
| `max_results` | `int` | `None` | 指定したドキュメント数を収集したら終了します (`auto_paginate=True` の場合にのみ適用されます) 。 |
| `max_wait_time` | `int` | `None` | 指定した秒数が経過したら終了します (`auto_paginate=True` の場合にのみ適用されます) 。 |

#### 手動ページネーションヘルパー

`auto_paginate=False` の場合、追加のデータがあると、レスポンスに `next` URL が含まれます。次のページを取得するには、これらのヘルパーメソッドを使用します:

* **`get_crawl_status_page(next_url)`** - 前のレスポンスに含まれる不透明な `next` URL を使用して、クロール結果の次のページを取得します。
* **`get_batch_scrape_status_page(next_url)`** - 前のレスポンスに含まれる不透明な `next` URL を使用して、バッチスクレイプ結果の次のページを取得します。

これらのメソッドは、元のステータス呼び出しと同じ型のレスポンスを返し、さらにページが残っている場合は新しい `next` URL を含みます。

#### クロール

最も手軽なのはウェイター方式の `crawl` を使うことです。もしくはジョブを開始して手動でページ処理を行ってください。

##### シンプルなクロール (自動ページネーション、デフォルト)

* 既定のフローについては[ウェブサイトをクロールする](#crawl-a-website)を参照してください。

##### ページネーションを制御した手動クロール

ジョブを開始し、`auto_paginate=False` を指定して 1 ページずつ取得します。後続のページを取得するには `get_crawl_status_page` を使用します。

```python Python theme={null}
crawl_job = client.start_crawl("https://example.com", limit=100)

# 最初のページを取得
status = client.get_crawl_status(
    crawl_job.id,
    pagination_config=PaginationConfig(auto_paginate=False)
)
print("First page:", len(status.data), "docs")

# get_crawl_status_pageを使用して後続のページを取得
while status.next:
    status = client.get_crawl_status_page(status.next)
    print("Next page:", len(status.data), "docs")
```

##### Manual crawl with limits (auto-pagination + early stop)

自動ページネーションは有効のまま、`max_pages`、`max_results`、または `max_wait_time` で早期停止します。

```python Python theme={null}
status = client.get_crawl_status(
    crawl_job.id,
    pagination_config=PaginationConfig(max_pages=2, max_results=50, max_wait_time=15),
)
print("クロール制限:", status.status, "ドキュメント数:", len(status.data), "次のページ:", status.next)
```

#### バッチスクレイプ

waiter メソッド `batch_scrape` を使うか、ジョブを開始して手動でページングします。

##### シンプルなバッチスクレイプ (自動ページネーション、デフォルト)

* 既定のフローは [Batch Scrape](https://docs.firecrawl.dev/ja/features/batch-scrape.md) を参照してください。

##### ページネーション制御付きの手動バッチスクレイピング

`auto_paginate=False` を指定してジョブを開始し、1ページずつ取得します。後続のページを取得するには `get_batch_scrape_status_page` を使用します。

```python Python theme={null}
batch_job = client.start_batch_scrape(urls)

# 最初のページを取得
status = client.get_batch_scrape_status(
    batch_job.id,
    pagination_config=PaginationConfig(auto_paginate=False)
)
print("First page:", len(status.data), "docs")

# get_batch_scrape_status_pageを使用して後続のページを取得
while status.next:
    status = client.get_batch_scrape_status_page(status.next)
    print("Next page:", len(status.data), "docs")
```

##### 制限付きの手動バッチスクレイプ (自動ページネーション + 早期停止)

自動ページネーションは有効にしたまま、`max_pages`、`max_results`、または `max_wait_time` で早期に停止します：

```python Python theme={null}
status = client.get_batch_scrape_status(
    batch_job.id,
    pagination_config=PaginationConfig(max_pages=2, max_results=100, max_wait_time=20),
)
print("バッチ制限:", status.status, "ドキュメント数:", len(status.data), "次:", status.next)
```

## エラーハンドリング

リクエストが失敗すると、SDK は何が原因かを説明するメッセージを含む例外を発生させます。これらの例外を捕捉し、アプリケーション内で失敗に対処できるように、呼び出しは `try`/`except` で囲んでください。

## 非同期クラス

非同期処理には `AsyncFirecrawl` クラスを使用します。メソッドは `Firecrawl` と同等ですが、メインスレッドをブロックしません。

```python Python theme={null}
import asyncio
from firecrawl import AsyncFirecrawl

async def main():
    firecrawl = AsyncFirecrawl(api_key="fc-YOUR-API-KEY")

    # スクレイピング
    doc = await firecrawl.scrape("https://firecrawl.dev", formats=["markdown"])  # type: ignore[arg-type]
    print(doc.get("markdown"))

    # 検索
    results = await firecrawl.search("firecrawl", limit=2)
    print(results.get("web", []))

    # クロール（開始とステータス）
    started = await firecrawl.start_crawl("https://docs.firecrawl.dev", limit=3)
    status = await firecrawl.get_crawl_status(started.id)
    print(status.status)

    # バッチスクレイピング（待機）
    job = await firecrawl.batch_scrape([
        "https://firecrawl.dev",
        "https://docs.firecrawl.dev",
    ], formats=["markdown"], poll_interval=1, timeout=60)
    print(job.status, job.completed, job.total)

asyncio.run(main())
```

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

async_firecrawl = AsyncFirecrawl(api_key="fc-YOUR-API-KEY")

parsed = await async_firecrawl.parse(
    b"<!DOCTYPE html><html><body><h1>Async Parse</h1></body></html>",
    filename="upload.html",
    content_type="text/html",
)
```

## ブラウザ

クラウドブラウザセッションを起動し、リモートでコードを実行できます。

### セッションの作成

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

app = Firecrawl(api_key="fc-YOUR-API-KEY")

session = app.browser()
print(session.id)             # セッションID
print(session.cdp_url)        # wss://cdp-proxy.firecrawl.dev/cdp/...
print(session.live_view_url)  # https://liveview.firecrawl.dev/...
```

### コードの実行

```python Python theme={null}
result = app.browser_execute(
    session.id,
    code='await page.goto("https://news.ycombinator.com")\ntitle = await page.title()\nprint(title)',
    language="python",
)
print(result.result)  # "Hacker News"
```

Python の代わりに JavaScript を実行する:

```python Python theme={null}
result = app.browser_execute(
    session.id,
    code='await page.goto("https://example.com"); const t = await page.title(); console.log(t);',
    language="node",
)
```

### プロファイル

セッション間でブラウザの状態 (クッキーや localStorage など) を保存して再利用します：

```python Python theme={null}
session = app.browser(
    ttl=600,
    profile={
        "name": "my-profile",
        "save_changes": True,
    },
)
```

### CDP 経由で接続する

Playwright をフルに制御するには、CDP URL を使用して直接接続します。

```python Python theme={null}
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp(session.cdp_url)
    context = browser.contexts[0]
    page = context.pages[0] if context.pages else context.new_page()

    page.goto("https://example.com")
    print(page.title())

    browser.close()
```

### セッションの一覧表示とクローズ

```python Python theme={null}
# アクティブなセッションを一覧表示
sessions = app.list_browsers(status="active")
for s in sessions.sessions:
    print(s.id, s.status, s.created_at)

# セッションをクローズ
app.delete_browser(session.id)
```

### スクレイピングに紐づいたインタラクティブセッション

スクレイピングの `job ID` を使用すると、そのスクレイピングで再現されたページコンテキストに対して引き続き操作できます。

* `interact(job_id, ...)` は、スクレイピングに紐づいたブラウザセッション内でコードを実行します。
* 最初の `interact` 呼び出しでは、スクレイピングコンテキストからセッションが自動的に初期化されます。
* 同じ `job ID` に対する後続の `interact` 呼び出しでは、そのブラウザのライブ状態が再利用されます。
* `stop_interaction(job_id)` は、操作が完了したらインタラクティブセッションを停止します。

```python Python theme={null}
doc = app.scrape(
    "https://example.com",
    actions=[{"type": "click", "selector": "a[href='/https/docs.firecrawl.dev/pricing']"}],
)

scrape_job_id = doc.metadata_typed.scrape_id
if not scrape_job_id:
    raise RuntimeError("Missing scrape job id")

run = app.interact(
    scrape_job_id,
    code="print(await page.url())",
    language="python",
    timeout=60,
)
print(run.stdout)

app.stop_interaction(scrape_job_id)
```

> Firecrawl API key が必要な AI agent ですか？自動オンボーディングの手順については、[firecrawl.dev/agent-onboarding/SKILL.md](https://www.firecrawl.dev/agent-onboarding/SKILL.md) をご覧ください。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.