spider-lib
A Rust-based web scraping framework inspired by Scrapy.
spider-lib is an asynchronous, concurrent web scraping library for Rust. It's designed to be a lightweight yet powerful tool for building and running scrapers for projects of any size. If you're familiar with Scrapy's architecture of Spiders, Middlewares, and Pipelines, you'll feel right at home.
Getting Started
To use spider-lib, add it to your project's Cargo.toml:
[]
= "0.2" # Check crates.io for the latest version
Quick Example
Here's a minimal example of a spider that scrapes quotes from quotes.toscrape.com.
For convenience, spider-lib offers a prelude that re-exports the most commonly used items.
// Use the prelude for easy access to common types and traits.
use *;
use ToSelector; // ToSelector is not in the prelude
;
async
Features
- Asynchronous & Concurrent:
spider-libprovides a high-performance, asynchronous web scraping framework built ontokio, leveraging an actor-like concurrency model for efficient task handling. - Crawl Statistics: Automatically collects and logs comprehensive statistics about the crawl's progress, including requests, responses (with status codes), items scraped, and downloaded bytes. The
StatCollectorcan also be accessed programmatically viacrawler.get_stats()for custom reporting and integration. - Graceful Shutdown: Ensures clean termination on
Ctrl+C, allowing in-flight tasks to complete and flushing all data. - Checkpoint and Resume: Allows saving the crawler's state (scheduler, pipelines) to a file and resuming the crawl later, supporting both manual and periodic automatic saves. This includes salvaging un-processed requests.
- Request Deduplication: Utilizes request fingerprinting to prevent duplicate requests from being processed, ensuring efficiency and avoiding redundant work.
- Familiar Architecture: Leverages a modular design with Spiders, Middlewares, and Item Pipelines, drawing inspiration from Scrapy.
- Configurable Concurrency: Offers fine-grained control over the number of concurrent downloads, parsing workers, and pipeline processing for optimized performance.
- Advanced Link Extraction: Includes a powerful
Responseobject method to comprehensively extract, resolve, and categorize various types of links from HTML content. - Fluent Configuration: A
CrawlerBuilderAPI simplifies the assembly and configuration of your web crawler.
For complete, runnable examples, please refer to the examples/ directory in this repository. You can run an example using cargo run --example <example_name> --features <features>, for instance: cargo run --example quotes --features "pipeline-json".
Configuration Examples
While spider-lib provides sensible defaults, you can finely tune its behavior by configuring middlewares, pipelines, and the crawler itself.
Middlewares
Middlewares inspect and modify requests and responses. They can be added to the CrawlerBuilder.
The following middlewares are included by default:
- Rate Limiting: Controls request rates to prevent server overload.
- Retries: Automatically retries failed or timed-out requests.
- User-Agent Rotation: Manages and rotates user agents.
- Referer Management: Handles the
Refererheader.
Additional middlewares are available via feature flags:
- Cookie Management: Persists cookies across requests to maintain sessions (
middleware-cookies). - HTTP Caching: Caches responses to accelerate development (
middleware-http-cache). - Respect Robots.txt: Adheres to
robots.txtrules (middleware-robots-txt).
CookieMiddleware
This middleware automatically manages cookies to maintain sessions across requests, which is essential for scraping sites that require logins. It is enabled via the middleware-cookies feature. For robust operation, it's also integrated with the checkpointing system, so cookie sessions are saved and restored along with the rest of the crawl state.
use *;
// Make sure to enable the `middleware-cookies` feature in Cargo.toml
use CookieMiddleware;
use CookieStore;
use Arc;
use Mutex;
// ... inside your main async function
let cookie_store = new;
let crawler = new // Assumes `YourSpider` is a defined Spider
.add_middleware
.build
.await?;
UserAgentMiddleware
This middleware manages and rotates User-Agent strings. It can be configured with different rotation strategies, User-Agent sources, and even apply different rules for different domains.
Available Strategies (UserAgentRotationStrategy):
Random: (Default) Selects a User-Agent randomly.Sequential: Cycles through the list of User-Agents in order.Sticky: On first encounter, a User-Agent is "stuck" to a domain for the entire crawl.StickySession: A User-Agent is "stuck" to a domain for a configured duration.
use *;
use ;
use Duration;
// ... inside your main async function
let ua_middleware = builder
// Set the default strategy for all domains
.strategy
// Set the default source of User-Agents
.source
// Set the session duration for the `StickySession` strategy
.session_duration
// Use a different User-Agent source specifically for "example.org"
.per_domain_source
// Use a different strategy for "example.com"
.per_domain_strategy
.build?;
RateLimitMiddleware
This middleware controls the request rate to avoid overloading servers. By default, it uses an adaptive limiter on a per-domain basis. You can configure it to use a fixed rate instead.
use *;
use ;
// ... inside your main async function
let rate_limit_middleware = builder
// Apply one rate limit across all domains
.scope
// Use a token bucket algorithm to allow 5 requests per second
.use_token_bucket_limiter
.build;
HttpCacheMiddleware
This middleware caches HTTP responses to disk, which can significantly speed up development and re-runs by avoiding redundant network requests. It's enabled via the middleware-http-cache feature.
use *;
// Make sure to enable the `middleware-http-cache` feature in Cargo.toml
use HttpCacheMiddleware;
use PathBuf;
// ... inside your main async function
let http_cache_middleware = builder
// Set a custom directory for storing cache files
.cache_dir
.build?;
RefererMiddleware
This middleware automatically manages the Referer HTTP header, simulating natural browsing behavior.
use *;
use RefererMiddleware;
// ... inside your main async function
let referer_middleware = new
// Ensure referer is only set for requests to the same origin
.same_origin_only
// Keep a maximum of 500 referer URLs in memory
.max_chain_length
// Do not include URL fragments in the referer header
.include_fragment;
RetryMiddleware
This middleware automatically retries failed requests based on HTTP status codes or network errors, using an exponential backoff strategy.
use *;
use RetryMiddleware;
use Duration;
// ... inside your main async function
let retry_middleware = new
// Allow up to 5 retry attempts
.max_retries
// Define which HTTP status codes should trigger a retry
.retry_http_codes
// Set the exponential backoff factor
.backoff_factor
// Cap the maximum delay between retries at 300 seconds (5 minutes)
.max_delay;
RobotsTxtMiddleware
This middleware respects robots.txt rules, preventing the crawler from accessing disallowed paths. It's enabled via the middleware-robots-txt feature.
use *;
// Make sure to enable the `middleware-robots-txt` feature in Cargo.toml
use RobotsTxtMiddleware;
use Duration;
// ... inside your main async function
let robots_txt_middleware = new
// Cache robots.txt rules for 12 hours
.cache_ttl
// Store up to 5000 robots.txt files in cache
.cache_capacity
// Set a timeout of 10 seconds for fetching robots.txt files
.request_timeout;
Pipelines
Item Pipelines are used for processing, filtering, or saving scraped items.
The following pipelines are included by default:
- Deduplication: Filters out duplicate items based on a configurable key.
- Console Writer: A simple pipeline for printing items to the console.
Exporter pipelines are available via feature flags:
- JSON / JSON Lines: Saves items to
.jsonor.jsonlfiles (pipeline-json). - CSV: Saves items to
.csvfiles (pipeline-csv). - SQLite: Saves items to a SQLite database (
pipeline-sqlite).
ConsoleWriterPipeline
A simple pipeline that prints each scraped item to the console. Useful for debugging.
use *;
use ConsoleWriterPipeline;
// ... inside your main async function
let console_pipeline = new;
DeduplicationPipeline
This pipeline filters out duplicate items based on a configurable set of fields.
use *;
use DeduplicationPipeline;
// ... inside your main async function
let deduplication_pipeline = new;
JsonWriterPipeline & JsonlWriterPipeline
These pipelines save scraped items to a file. They are enabled with the pipeline-json feature.
JsonWriterPipeline: Collects all items and writes them to a single, pretty-printed JSON array at the end of the crawl.JsonlWriterPipeline: Writes each item as a separate JSON object on a new line, which is efficient for streaming large amounts of data.
use *;
// Make sure to enable the `pipeline-json` feature in Cargo.toml
use JsonWriterPipeline;
use JsonlWriterPipeline;
// ... inside your main async function
let json_pipeline = new?;
let jsonl_pipeline = new?;
let crawler = new // Assumes `YourSpider` is a defined Spider
.add_pipeline
.add_pipeline
// ... configure other middlewares
.build
.await?;
CsvExporterPipeline
This pipeline saves items to a CSV file, enabled with the pipeline-csv feature. The CSV headers are automatically inferred from the fields of the first item scraped.
use *;
// Make sure to enable the `pipeline-csv` feature in Cargo.toml
use CsvExporterPipeline;
// ... inside your main async function
let csv_pipeline = new?;
let crawler = new // Assumes `YourSpider` is a defined Spider
.add_pipeline
// ... configure other middlewares
.build
.await?;
SqliteWriterPipeline
This pipeline saves items to a SQLite database, enabled with the pipeline-sqlite feature. The table schema is automatically inferred from the fields of the first item scraped.
use *;
// Make sure to enable the `pipeline-sqlite` feature in Cargo.toml
use SqliteWriterPipeline;
// ... inside your main async function
let sqlite_pipeline = new?;
let crawler = new // Assumes `YourSpider` is a defined Spider
.add_pipeline
// ... configure other middlewares
.build
.await?;
Crawler Settings
You can configure the core behavior of the crawler, such as concurrency and checkpointing.
Checkpointing & Resuming
This feature allows a crawl to be paused and resumed later. When the crawler starts, it will load the state from the checkpoint file if it exists. This feature is enabled by the checkpoint flag.
use *;
use Duration;
// ... inside your main async function
let crawler = new // Assumes `YourSpider` is a defined Spider
// Set the path to save/load the checkpoint file
.with_checkpoint_path
// Automatically save the state every 10 minutes
.with_checkpoint_interval
// ... configure your other middlewares, and pipelines
.build
.await?;
Concurrency
You can control the parallelism of different parts of the crawl to manage system resources and target server load.
use *;
// ... inside your main async function
let crawler = new // Assumes `YourSpider` is a defined Spider
// Set the maximum number of concurrent downloads
.max_concurrent_downloads
// Set the number of CPU workers for parsing responses
.max_parser_workers
// Set the maximum number of items to be processed by pipelines concurrently
.max_concurrent_pipelines
// ... configure your other middlewares, and pipelines
.build
.await?;
Feature Flags
spider-lib uses feature flags to keep the core library lightweight while allowing for optional functionality. To use a feature, add it to your Cargo.toml.
| Feature Flag | Enables | Description |
|---|---|---|
| Pipelines | ||
pipeline-json |
JsonWriterPipeline, JsonlWriterPipeline |
Saves items to .json or .jsonl files. |
pipeline-csv |
CsvExporterPipeline |
Saves items to a .csv file. |
pipeline-sqlite |
SqliteWriterPipeline |
Saves items to a SQLite database. |
| Middlewares | ||
middleware-cookies |
CookieMiddleware |
Manages cookies and sessions across requests. |
middleware-http-cache |
HttpCacheMiddleware |
Caches HTTP responses to disk to speed up development. |
middleware-robots-txt |
RobotsTxtMiddleware |
Respects robots.txt rules for websites. |
| Core | ||
checkpoint |
Checkpointing System | Enables saving and resuming crawl state. |
Example of enabling multiple features:
[]
= { = "0.3", = ["pipeline-json", "middleware-http-cache", "checkpoint"] }