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

# Rust

> Evocrawl Rust SDK は、Web サイトを簡単に Markdown に変換できる EvoCrawl API のラッパーです。

<div id="installation">
  ## インストール
</div>

公式の Rust SDK は、Evocrawl のモノレポ内にある [apps/rust-sdk](https://github.com/superaihuman/evocrawl/tree/main/apps/rust-sdk) で管理されています。

Evocrawl Rust SDK をインストールするには、[crates.io](https://crates.io/crates/evocrawl) から依存関係を追加します。

```toml theme={null}
[dependencies]
evocrawl = "2"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
```

または Cargo でインストールします。

```bash theme={null}
cargo add evocrawl
cargo add tokio --features full
cargo add serde_json
```

<Note>Rust 1.70以降が必要です。</Note>

<div id="usage">
  ## 使用方法
</div>

1. [evocrawl.dev](https://evocrawl.com) でAPIキーを取得します
2. APIキーを `EVOCRAWL_API_KEY` という名前の環境変数に設定するか、`Client::new(...)` に直接渡します

以下は、SDKを使った簡単な例です。

```rust theme={null}
use evocrawl::{Client, CrawlOptions, 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://evocrawl.com",
        ScrapeOptions {
            formats: Some(vec![Format::Markdown]),
            ..Default::default()
        },
    ).await?;

    let job = client.crawl(
        "https://evocrawl.com",
        CrawlOptions {
            limit: Some(5),
            ..Default::default()
        },
    ).await?;

    println!("{}", doc.markdown.unwrap_or_default());
    println!("Crawled pages: {}", job.data.len());
    Ok(())
}
```

<div id="scraping-a-url">
  ### URLのスクレイピング
</div>

単一のURLをスクレイピングするには、`scrape`メソッドを使用します。

```rust theme={null}
use evocrawl::{Client, ScrapeOptions, Format};

let doc = client.scrape(
    "https://evocrawl.com",
    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);
}
```

<div id="json-extraction">
  #### JSON抽出
</div>

`scrape_with_schema` を使用して、構造化されたJSONを抽出します:

```rust theme={null}
use evocrawl::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 抽出を設定することもできます:

```rust theme={null}
use evocrawl::{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);
```

<div id="crawling-a-website">
  ### Web サイトのクロール
</div>

Web サイトをクロールして完了を待つには、`crawl` を使用します。

```rust theme={null}
use evocrawl::{Client, CrawlOptions, ScrapeOptions, Format};

let job = client.crawl(
    "https://evocrawl.com",
    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);
    }
}
```

<div id="start-a-crawl">
  ### クロールを開始する
</div>

`start_crawl` を使うと、待たずにジョブを開始できます。

```rust theme={null}
use evocrawl::{Client, CrawlOptions};

let start = client.start_crawl(
    "https://evocrawl.com",
    CrawlOptions {
        limit: Some(100),
        ..Default::default()
    },
).await?;

println!("Job ID: {}", start.id);
```

<div id="checking-crawl-status">
  ### クロールのステータスを確認
</div>

`get_crawl_status`でクロールの進行状況を確認できます。

```rust theme={null}
let status = client.get_crawl_status(&start.id).await?;
println!("Status: {:?}", status.status);
println!("Progress: {}/{}", status.completed, status.total);
```

<div id="cancelling-a-crawl">
  ### クロールをキャンセルする
</div>

実行中のクロールは `cancel_crawl` でキャンセルできます。

```rust theme={null}
let result = client.cancel_crawl(&start.id).await?;
println!("{:?}", result);
```

<div id="checking-crawl-errors">
  ### クロールエラーの確認
</div>

`get_crawl_errors` でクロールジョブのエラーを取得します。

```rust theme={null}
let errors = client.get_crawl_errors(&start.id).await?;
println!("{:?}", errors);
```

<div id="mapping-a-website">
  ### Web サイトをマッピングする
</div>

`map` を使用して Web サイト内のリンクを見つけます。

```rust theme={null}
use evocrawl::{Client, MapOptions};

let response = client.map(
    "https://evocrawl.com",
    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` を使用します:

```rust theme={null}
let urls = client.map_urls("https://evocrawl.com", None).await?;
for url in &urls {
    println!("{}", url);
}
```

<div id="searching-the-web">
  ### Webを検索する
</div>

`search` を使うと、任意の設定で検索できます。

```rust theme={null}
use evocrawl::{Client, SearchOptions};

let results = client.search(
    "evocrawl web scraping",
    SearchOptions {
        limit: Some(10),
        ..Default::default()
    },
).await?;

if let Some(web) = results.data.web {
    for item in web {
        match item {
            evocrawl::SearchResultOrDocument::WebResult(r) => {
                println!("{} - {}", r.url, r.title.unwrap_or_default());
            }
            evocrawl::SearchResultOrDocument::Document(d) => {
                println!("{}", d.markdown.unwrap_or_default());
            }
        }
    }
}
```

スクレイピング済みのドキュメントを直接返す便利なメソッドを使う場合:

```rust theme={null}
let docs = client.search_and_scrape("evocrawl web scraping", 5).await?;
for doc in &docs {
    println!("{}", doc.markdown.as_deref().unwrap_or(""));
}
```

<div id="batch-scraping">
  ### バッチスクレイピング
</div>

`batch_scrape` を使用して、複数のURLを並列でスクレイピングします。

```rust theme={null}
use evocrawl::{Client, BatchScrapeOptions, ScrapeOptions, Format};

let urls = vec![
    "https://evocrawl.com".to_string(),
    "https://evocrawl.com/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(""));
}
```

<div id="agent">
  ### Agent
</div>

`agent` を使って AI エージェントを実行します。

```rust theme={null}
use evocrawl::{Client, AgentOptions};

let result = client.agent(
    AgentOptions {
        prompt: "Find the pricing plans for Evocrawl and compare them".to_string(),
        ..Default::default()
    },
).await?;

println!("{:?}", result.data);
```

構造化された出力用のJSON schema:

```rust theme={null}
use evocrawl::{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://evocrawl.com".to_string()],
    "Extract pricing plan details",
    schema,
).await?;

if let Some(data) = result {
    for plan in &data.plans {
        println!("{}: {}", plan.name, plan.price);
    }
}
```

<div id="scrape-bound-interactive-session">
  ## スクレイピングに紐づいたインタラクティブセッション
</div>

スクレイピングジョブIDを使用して、同じコンテキストで後続のブラウザコードを実行できます。

* `interact(...)` は、スクレイピングに紐づいたブラウザセッション内でコードまたはプロンプトを実行します。
* `stop_interaction(...)` は、作業完了後にインタラクティブセッションを停止します。

```rust theme={null}
use evocrawl::{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?;
```

<div id="configuration">
  ## 設定
</div>

`Client::new(...)` と `Client::new_selfhosted(...)` でクライアントを作成します。

| Option                                     | Description                                                    |
| ------------------------------------------ | -------------------------------------------------------------- |
| `Client::new(api_key)`                     | Evocrawl のクラウドサービス (`https://api.evocrawl.com`) 用のクライアントを作成します |
| `Client::new_selfhosted(api_url, api_key)` | セルフホストの Evocrawl インスタンス用のクライアントを作成します                          |

```rust theme={null}
use evocrawl::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>,
)?;
```

<div id="environment-variable">
  ### 環境変数
</div>

キーを直接渡す代わりに、`EVOCRAWL_API_KEY` 環境変数を設定してください。

```bash theme={null}
export EVOCRAWL_API_KEY=fc-YOUR-API-KEY
```

```rust theme={null}
let api_key = std::env::var("EVOCRAWL_API_KEY")
    .expect("EVOCRAWL_API_KEY must be set");
let client = Client::new(api_key)?;
```

<div id="poll-intervals">
  ### ポーリング間隔
</div>

同期メソッド (`crawl`、`batch_scrape`、`agent`) は、完了するまでポーリングを続けます。ポーリング間隔は、`options` 構造体でカスタマイズできます。

```rust theme={null}
use evocrawl::CrawlOptions;

let options = CrawlOptions {
    limit: Some(50),
    poll_interval: Some(3000), // 3秒ごとにポーリング（デフォルト: 2000ms）
    ..Default::default()
};
```

<div id="error-handling">
  ## エラー処理
</div>

この SDK は、`Error`、`Debug`、`Display` を実装する `EvocrawlError` 列挙型を使用します。すべてのメソッドは `Result<T, EvocrawlError>` を返します。

```rust theme={null}
use evocrawl::{Client, EvocrawlError};

match client.scrape("https://example.com", None).await {
    Ok(doc) => println!("{}", doc.markdown.unwrap_or_default()),
    Err(EvocrawlError::HttpRequestFailed(action, status, msg)) => {
        eprintln!("HTTP {}: {} ({})", status, msg, action);
    }
    Err(EvocrawlError::APIError(action, api_err)) => {
        eprintln!("API error ({}): {}", action, api_err.error);
    }
    Err(EvocrawlError::JobFailed(msg)) => {
        eprintln!("Job failed: {}", msg);
    }
    Err(EvocrawlError::Misuse(msg)) => {
        eprintln!("SDK misuse: {}", msg);
    }
    Err(e) => eprintln!("Error: {}", e),
}
```

> EvoCrawl API キーを必要とする AI エージェントですか？自動オンボーディング手順については、[evocrawl.dev/agent-onboarding/SKILL.md](https://www.evocrawl.com/agent-onboarding/SKILL.md) を参照してください。
