2 个版本

0.1.1 2024年7月12日
0.1.0 2024年7月12日

#839 in 网络编程

GPL-2.0-or-later

23KB
255

Firecrawl Rust SDK

Firecrawl Rust SDK 是一个库,允许您轻松爬取和抓取网站,并以适合与语言模型(LLMs)一起使用的格式输出数据。它为与 Firecrawl API 交互提供了一个简单直观的接口。

安装

要安装 Firecrawl Rust SDK,请在您的 Cargo.toml 文件中添加以下内容

[dependencies]
firecrawl_rs = "^0.1"
tokio = { version = "^1", features = ["full"] }
serde = { version = "^1.0", features = ["derive"] }
serde_json = "^1.0"
uuid = { version = "^1.10", features = ["v4"] }

[build-dependencies]
tokio = { version = "1", features = ["full"] }

将其添加到您的代码库中。

用法

  1. firecrawl.dev 获取 API 密钥
  2. 将 API 密钥设置为名为 FIRECRAWL_API_KEY 的环境变量,或将它作为参数传递给 FirecrawlApp 结构体。

以下是如何在 example.rs 中使用 SDK 的示例:以下所有示例均可以此开始

use firecrawl_rs::FirecrawlApp;

#[tokio::main]
async fn main() {
    // Initialize the FirecrawlApp with the API key
    let api_key = ...;
    let api_url = ...;
    let app = FirecrawlApp::new(api_key, api_url).expect("Failed to initialize FirecrawlApp");

    // your code here...
}

抓取 URL

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

// Example scrape code...
let scrape_result = app.scrape_url("https://example.com", None).await;
match scrape_result {
    Ok(data) => println!("Scrape Result:\n{}", data["markdown"]),
    Err(e) => eprintln!("Scrape failed: {}", e),
}

从 URL 中提取结构化数据

通过 LLM 提取,您可以轻松地从任何 URL 中提取结构化数据。我们支持 Serde 进行 JSON 模式验证,使您更容易使用。以下是使用方法

let json_schema = json!({
    "type": "object",
    "properties": {
        "top": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "title": {"type": "string"},
                    "points": {"type": "number"},
                    "by": {"type": "string"},
                    "commentsURL": {"type": "string"}
                },
                "required": ["title", "points", "by", "commentsURL"]
            },
            "minItems": 5,
            "maxItems": 5,
            "description": "Top 5 stories on Hacker News"
        }
    },
    "required": ["top"]
});

let llm_extraction_params = json!({
    "extractorOptions": {
        "extractionSchema": json_schema,
        "mode": "llm-extraction"
    },
    "pageOptions": {
        "onlyMainContent": true
    }
});

// Example scrape code...
let llm_extraction_result = app
    .scrape_url("https://news.ycombinator.com", Some(llm_extraction_params))
    .await;
match llm_extraction_result {
    Ok(data) => println!("LLM Extraction Result:\n{}", data["llm_extraction"]),
    Err(e) => eprintln!("LLM Extraction failed: {}", e),
}

搜索查询

用于在网络上搜索,获取最相关的结果,抓取每个页面,并返回 markdown 格式的内容。

// Example query search code...
let query = "what is mendable?";
let search_result = app.search(query).await;
match search_result {
    Ok(data) => println!("Search Result:\n{}", data),
    Err(e) => eprintln!("Search failed: {}", e),
}

爬取网站

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

wait_until_done参数决定了方法是否在返回结果之前等待爬取作业完成。如果设置为true,则方法将定期检查爬取作业的状态,直到完成或达到指定的timeout(秒数)。如果设置为false,则方法将立即返回作业ID,您可以使用check_crawl_status方法手动检查爬取作业的状态。

let random_uuid = String::from(Uuid::new_v4());
let idempotency_key = Some(random_uuid); // optional idempotency key
let crawl_params = json!({
    "crawlerOptions": {
        "excludes": ["blog/*"]
    }
});

// Example crawl code...
let crawl_result = app
    .crawl_url("https://example.com", Some(crawl_params), true, 2, idempotency_key)
    .await;
match crawl_result {
    Ok(data) => println!("Crawl Result:\n{}", data),
    Err(e) => eprintln!("Crawl failed: {}", e),
}

如果wait_until_done设置为true,则crawl_url方法将在作业完成后返回爬取结果。如果作业失败或停止,将抛出异常。

检查爬取状态

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

let job_id = crawl_result["jobId"].as_str().expect("Job ID not found");
let status = app.check_crawl_status(job_id).await;
match status {
    Ok(data) => println!("Crawl Status:\n{}", data),
    Err(e) => eprintln!("Failed to check crawl status: {}", e),
}

错误处理

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

使用Cargo运行测试

为了确保Firecrawl Rust SDK的功能,我们已包含使用cargo的端到端测试。这些测试涵盖了SDK的各个方面,包括URL抓取、网络搜索和网站爬取。

运行测试

要运行测试,请执行以下命令

$ export $(xargs < ./tests/.env)
$ cargo test --test e2e_with_auth

贡献

欢迎对Firecrawl Rust SDK的贡献!如果您发现任何问题或有改进建议,请在GitHub仓库中提交问题或拉取请求。

许可

Firecrawl Rust SDK是开源的,并使用AGPL许可证发布。

依赖

~6–18MB
~254K SLoC