Documentation Index
Fetch the complete documentation index at: https://firecrawl-mog-search-exclude-include-domains.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
公式の Rust SDK は、Firecrawl のモノレポ内にある apps/rust-sdk で管理されています。
Firecrawl Rust SDK をインストールするには、crates.io から依存関係を追加します。
[dependencies]
firecrawl = "2"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
または Cargo でインストールします。
cargo add firecrawl
cargo add tokio --features full
cargo add serde_json
- firecrawl.dev でAPIキーを取得します
- APIキーを
FIRECRAWL_API_KEY という名前の環境変数に設定するか、Client::new(...) に直接渡します
ページをスクレイピングし、そのMarkdownを出力します:
use firecrawl::{Client, ScrapeOptions, Format};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new("fc-YOUR-API-KEY")?;
let doc = client.scrape(
"https://firecrawl.dev",
ScrapeOptions {
formats: Some(vec![Format::Markdown]),
..Default::default()
},
).await?;
println!("{}", doc.markdown.unwrap_or_default());
Ok(())
}
以下のセクションでは、クロール、マッピング、検索、その他のSDKメソッドについて説明します。
単一のURLをスクレイピングするには、scrapeメソッドを使用します。
use firecrawl::{Client, ScrapeOptions, Format};
let doc = client.scrape(
"https://firecrawl.dev",
ScrapeOptions {
formats: Some(vec![Format::Markdown, Format::Html]),
only_main_content: Some(true),
wait_for: Some(5000),
..Default::default()
},
).await?;
println!("{}", doc.markdown.unwrap_or_default());
if let Some(meta) = &doc.metadata {
println!("{:?}", meta.title);
}
scrape_with_schema を使用して、構造化されたJSONを抽出します:
use firecrawl::Client;
use serde_json::json;
let schema = json!({
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number" }
}
});
let data = client.scrape_with_schema(
"https://example.com/product",
schema,
Some("Extract the product name and price"),
).await?;
println!("{}", serde_json::to_string_pretty(&data)?);
または、ScrapeOptions で直接 JSON 抽出を設定することもできます:
use firecrawl::{Client, ScrapeOptions, Format, JsonOptions};
use serde_json::json;
let doc = client.scrape(
"https://example.com/product",
ScrapeOptions {
formats: Some(vec![Format::Json]),
json_options: Some(JsonOptions {
schema: Some(json!({
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number" }
}
})),
prompt: Some("Extract the product name and price".to_string()),
..Default::default()
}),
..Default::default()
},
).await?;
println!("{:?}", doc.json);
parse を使うと、ローカルファイル (.html、.htm、.pdf、.docx、.doc、.odt、.rtf、.xlsx、.xls) を multipart form data として /v2/parse にアップロードできます。この endpoint は、指定したフォーマットを含む Document を返します。
ParseOptions では、/v2/parse が受け付けないスクレイピング専用のフィールド (actions、waitFor、location、mobile、screenshot、branding、changeTracking など) を意図的に除外しています。
メモリ上のバイト列、またはパスから直接 ParseFile を作成します。
use firecrawl::{Client, ParseFile, ParseFormat, ParseOptions};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new("fc-YOUR-API-KEY")?;
let file = ParseFile::from_bytes(
"upload.html",
b"<!DOCTYPE html><html><body><h1>Rust Parse</h1></body></html>".to_vec(),
)
.with_content_type("text/html");
let options = ParseOptions {
formats: Some(vec![ParseFormat::Markdown, ParseFormat::Html]),
only_main_content: Some(true),
..Default::default()
};
let doc = client.parse(file, Some(options)).await?;
println!("{}", doc.markdown.unwrap_or_default());
Ok(())
}
または、ディスクからファイルを読み込み、オプションは省略します:
use firecrawl::{Client, ParseFile};
let client = Client::new("fc-YOUR-API-KEY")?;
let file = ParseFile::from_path("./report.pdf")?;
let doc = client.parse(file, None).await?;
println!("{}", doc.markdown.unwrap_or_default());
| Constructor | 説明 |
|---|
ParseFile::from_bytes(filename, bytes) | ファイル名とメモリ上のバイト列から生成 |
ParseFile::from_path(path) | ディスクからバイト列を読み込み、ファイル名を取得 |
.with_content_type(content_type) | MIME タイプのヒントを付与 (例: text/html, application/pdf) |
利用可能なフィールド (すべて任意、ワイヤ形式では camelCase) :
formats: Vec<ParseFormat> — Markdown、Html、RawHtml、Links、Images、Summary、Json、Attributes のいずれか
only_main_content: bool
include_tags: Vec<String> / exclude_tags: Vec<String>
headers: HashMap<String, String>
timeout: u32 (ms)
parsers: Vec<ParserConfig> (例: PDF パーサーの設定)
skip_tls_verification: bool
remove_base64_images: bool
fast_mode: bool
block_ads: bool
proxy: ParseProxyType (Basic または Auto)
json_options: JsonOptions
attribute_selectors: Vec<AttributeSelector>
zero_data_retention: bool
integration: String, origin: String, use_mock: String
Web サイトをクロールして完了を待つには、crawl を使用します。
use firecrawl::{Client, CrawlOptions, ScrapeOptions, Format};
let job = client.crawl(
"https://firecrawl.dev",
CrawlOptions {
limit: Some(50),
max_discovery_depth: Some(3),
scrape_options: Some(ScrapeOptions {
formats: Some(vec![Format::Markdown]),
..Default::default()
}),
..Default::default()
},
).await?;
println!("Status: {:?}", job.status);
println!("Progress: {}/{}", job.completed, job.total);
for page in &job.data {
if let Some(meta) = &page.metadata {
println!("{:?}", meta.source_url);
}
}
start_crawl を使うと、待たずにジョブを開始できます。
use firecrawl::{Client, CrawlOptions};
let start = client.start_crawl(
"https://firecrawl.dev",
CrawlOptions {
limit: Some(100),
..Default::default()
},
).await?;
println!("Job ID: {}", start.id);
get_crawl_statusでクロールの進行状況を確認できます。
let status = client.get_crawl_status(&start.id).await?;
println!("Status: {:?}", status.status);
println!("Progress: {}/{}", status.completed, status.total);
実行中のクロールは cancel_crawl でキャンセルできます。
let result = client.cancel_crawl(&start.id).await?;
println!("{:?}", result);
get_crawl_errors でクロールジョブのエラーを取得します。
let errors = client.get_crawl_errors(&start.id).await?;
println!("{:?}", errors);
map を使用して Web サイト内のリンクを見つけます。
use firecrawl::{Client, MapOptions};
let response = client.map(
"https://firecrawl.dev",
MapOptions {
limit: Some(100),
search: Some("blog".to_string()),
..Default::default()
},
).await?;
for link in &response.links {
println!("{} - {}", link.url, link.title.as_deref().unwrap_or(""));
}
URL のみのシンプルな結果を得るには、map_urls を使用します:
let urls = client.map_urls("https://firecrawl.dev", None).await?;
for url in &urls {
println!("{}", url);
}
search を使うと、任意の設定で検索できます。
use firecrawl::{Client, SearchOptions};
let results = client.search(
"firecrawl web scraping",
SearchOptions {
limit: Some(10),
..Default::default()
},
).await?;
if let Some(web) = results.data.web {
for item in web {
match item {
firecrawl::SearchResultOrDocument::WebResult(r) => {
println!("{} - {}", r.url, r.title.unwrap_or_default());
}
firecrawl::SearchResultOrDocument::Document(d) => {
println!("{}", d.markdown.unwrap_or_default());
}
}
}
}
スクレイピング済みのドキュメントを直接返す便利なメソッドを使う場合:
let docs = client.search_and_scrape("firecrawl web scraping", 5).await?;
for doc in &docs {
println!("{}", doc.markdown.as_deref().unwrap_or(""));
}
batch_scrape を使用して、複数のURLを並列でスクレイピングします。
use firecrawl::{Client, BatchScrapeOptions, ScrapeOptions, Format};
let urls = vec![
"https://firecrawl.dev".to_string(),
"https://firecrawl.dev/blog".to_string(),
];
let job = client.batch_scrape(
urls,
BatchScrapeOptions {
options: Some(ScrapeOptions {
formats: Some(vec![Format::Markdown]),
..Default::default()
}),
..Default::default()
},
).await?;
for doc in &job.data {
println!("{}", doc.markdown.as_deref().unwrap_or(""));
}
agent を使って AI エージェントを実行します。
use firecrawl::{Client, AgentOptions};
let result = client.agent(
AgentOptions {
prompt: "Find the pricing plans for Firecrawl and compare them".to_string(),
..Default::default()
},
).await?;
println!("{:?}", result.data);
構造化された出力用のJSON schema:
use firecrawl::{Client, AgentOptions, AgentModel};
use serde::Deserialize;
use serde_json::json;
#[derive(Debug, Deserialize)]
struct PricingPlan {
name: String,
price: String,
}
#[derive(Debug, Deserialize)]
struct PricingData {
plans: Vec<PricingPlan>,
}
let schema = json!({
"type": "object",
"properties": {
"plans": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "string" }
}
}
}
}
});
let result: Option<PricingData> = client.agent_with_schema(
vec!["https://firecrawl.dev".to_string()],
"Extract pricing plan details",
schema,
).await?;
if let Some(data) = result {
for plan in &data.plans {
println!("{}: {}", plan.name, plan.price);
}
}
スクレイピングに紐づいたインタラクティブセッション
スクレイピングジョブIDを使用して、同じコンテキストで後続のブラウザコードを実行できます。
interact(...) は、スクレイピングに紐づいたブラウザセッション内でコードまたはプロンプトを実行します。
stop_interaction(...) は、作業完了後にインタラクティブセッションを停止します。
use firecrawl::{Client, ScrapeExecuteOptions, ScrapeExecuteLanguage};
let scrape_job_id = "550e8400-e29b-41d4-a716-446655440000";
// ブラウザセッションでコードを実行する
let run = client.interact(
scrape_job_id,
ScrapeExecuteOptions {
code: Some("console.log(await page.title())".to_string()),
language: Some(ScrapeExecuteLanguage::Node),
timeout: Some(60),
..Default::default()
},
).await?;
println!("{:?}", run.stdout);
// または自然言語プロンプトを使用する
let run = client.interact(
scrape_job_id,
ScrapeExecuteOptions {
prompt: Some("Click the pricing tab and summarize the plans".to_string()),
..Default::default()
},
).await?;
// 完了したらセッションを停止する
client.stop_interaction(scrape_job_id).await?;
Client::new(...) と Client::new_selfhosted(...) でクライアントを作成します。
| Option | Description |
|---|
Client::new(api_key) | Firecrawl のクラウドサービス (https://api.firecrawl.dev) 用のクライアントを作成します |
Client::new_selfhosted(api_url, api_key) | セルフホストの Firecrawl インスタンス用のクライアントを作成します |
use firecrawl::Client;
// クラウドサービス
let client = Client::new("fc-your-api-key")?;
// セルフホスト
let client = Client::new_selfhosted(
"http://localhost:3002",
Some("fc-your-api-key"),
)?;
// 認証なしのセルフホスト
let client = Client::new_selfhosted(
"http://localhost:3002",
None::<&str>,
)?;
キーを直接渡す代わりに、FIRECRAWL_API_KEY 環境変数を設定してください。
export FIRECRAWL_API_KEY=fc-YOUR-API-KEY
let api_key = std::env::var("FIRECRAWL_API_KEY")
.expect("FIRECRAWL_API_KEY must be set");
let client = Client::new(api_key)?;
同期メソッド (crawl、batch_scrape、agent) は、完了するまでポーリングを続けます。ポーリング間隔は、options 構造体でカスタマイズできます。
use firecrawl::CrawlOptions;
let options = CrawlOptions {
limit: Some(50),
poll_interval: Some(3000), // 3秒ごとにポーリング(デフォルト: 2000ms)
..Default::default()
};
この SDK は、Error、Debug、Display を実装する FirecrawlError 列挙型を使用します。すべてのメソッドは Result<T, FirecrawlError> を返します。
use firecrawl::{Client, FirecrawlError};
match client.scrape("https://example.com", None).await {
Ok(doc) => println!("{}", doc.markdown.unwrap_or_default()),
Err(FirecrawlError::HttpRequestFailed(action, status, msg)) => {
eprintln!("HTTP {}: {} ({})", status, msg, action);
}
Err(FirecrawlError::APIError(action, api_err)) => {
eprintln!("API error ({}): {}", action, api_err.error);
}
Err(FirecrawlError::JobFailed(msg)) => {
eprintln!("Job failed: {}", msg);
}
Err(FirecrawlError::Misuse(msg)) => {
eprintln!("SDK misuse: {}", msg);
}
Err(e) => eprintln!("Error: {}", e),
}
Firecrawl API キーを必要とする AI エージェントですか?自動オンボーディング手順については、firecrawl.dev/agent-onboarding/SKILL.md を参照してください。