Web Scraping in Rust: Build a Crawler With reqwest and scraper
Your first Rust scraper calls reqwest::get on a Wikipedia article, prints the response body, and gets this:
403 Forbidden Please set a user-agent and respect our robot policy https://w.wiki/4wJS.
The request reached the server, but reqwest did not send a User-Agent header. Wikipedia rejects requests without one. Fixing that gets you past the first failure, not every failure: spawning parsing work as tokio tasks produces a thread-safety compile error, and protected sites can reject requests even with a browser User-Agent.
This guide builds a crawler for books.toscrape.com, a public scraping sandbox. You will fetch listing pages, extract product links, request details concurrently, and route blocked requests through a fallback. The examples and outputs come from builds and runs dated November 28, 2026.
Set Up the Project
Create the project and add the HTTP client, HTML parser, async stream utilities, and tokio runtime:
cargo new books-scraper && cd books-scraper
cargo add reqwest scraper futures
cargo add tokio --features macros,rt-multi-thread
The dependency versions used here are reqwest 0.13.5, scraper 0.29.0, futures 0.3.34, and tokio 1.54.1.
In reqwest 0.13, the default TLS backend is rustls with aws-lc-rs. Its initial build compiles C code. If that dependency fails to build on your machine, configure reqwest to use the operating system’s TLS implementation instead:
reqwest = { version = "0.13", default-features = false, features = ["native-tls", "charset", "http2"] }
Wall 1: A Missing User-Agent Causes a 403
Start by inspecting what your client actually sends. A plain reqwest::get against https://httpbin.org/headers returns the request headers as seen by that endpoint:
{
"headers": {
"Accept": "*/*",
"Host": "httpbin.org"
}
}
There is no User-Agent. Wikipedia and GitHub’s REST API reject requests without that header. Both expect you to identify your client; Wikimedia’s robot policy also asks for contact details.
Build a reusable Client with a User-Agent and a timeout rather than configuring each request separately:
let client = Client::builder()
.user_agent("books-scraper/0.1 (+mailto:you@example.com)")
.timeout(Duration::from_secs(30))
.build()?;
The client maintains a connection pool, with shared internal state behind an Arc. Cloning it is cheap and preserves access to that pool. Creating a new client for every request prevents connection reuse across requests and can require fresh TLS connections.
A User-Agent identifies your application. It does not make reqwest behave like the browser named in the header, which matters when you reach the third wall.
Parse a Listing Page With scraper
The scraper crate uses html5ever, the HTML parser from the Servo project, and exposes CSS selectors for querying the parsed document.
On the sandbox listing pages, each product is an article.product_pod. The product link’s title attribute contains the title, and li.next a points to the next listing page. The parser below extracts owned product data and resolves links against the current page URL:
use std::sync::LazyLock;
use std::time::Duration;
use futures::stream::{self, StreamExt};
use reqwest::{Client, StatusCode, Url};
use scraper::{ElementRef, Html, Selector};
type BoxError = Box<dyn std::error::Error + Send + Sync>;
fn sel(css: &str) -> Selector {
Selector::parse(css).unwrap()
}
static CARD: LazyLock<Selector> = LazyLock::new(|| sel("article.product_pod"));
static LINK: LazyLock<Selector> = LazyLock::new(|| sel("h3 a"));
static PRICE: LazyLock<Selector> = LazyLock::new(|| sel(".price_color"));
static NEXT: LazyLock<Selector> = LazyLock::new(|| sel("li.next a"));
#[derive(Debug)]
struct Book {
title: String,
price: String,
url: Url,
}
fn text_of(el: ElementRef) -> String {
el.text().collect::<String>().trim().to_string()
}
fn parse_listing(body: &str, page_url: &Url) -> (Vec<Book>, Option<Url>) {
let doc = Html::parse_document(body);
let books = doc
.select(&CARD)
.filter_map(|card| {
let link = card.select(&LINK).next()?;
Some(Book {
title: link.attr("title")?.to_string(),
price: text_of(card.select(&PRICE).next()?),
url: page_url.join(link.attr("href")?).ok()?,
})
})
.collect();
let next = doc
.select(&NEXT)
.next()
.and_then(|a| a.attr("href"))
.and_then(|href| page_url.join(href).ok());
(books, next)
}
Three implementation details matter:
- Parse selectors once.
LazyLock, stable since Rust 1.80, initializes eachSelectoron its first use. Anunwrapis reasonable for fixed selectors you control, but a typo still panics when that selector is first accessed. Exercise those paths before starting a long crawl. - Resolve links with
Url::join. A value such asa-light-in-the-attic_1000/index.htmlis relative to the listing page. URL resolution also handles../path segments. - Skip incomplete cards deliberately. Using
filter_mapwith?drops a product when a required field, such as its price, is missing. That keeps the crawl running, but means malformed cards do not appear in the output.
Keep parse_listing synchronous. It creates the document, extracts owned String and Url values, and drops the parser state before returning. That boundary prevents the next compiler error.
Wall 2: “future cannot be sent between threads safely”
A natural first implementation puts fetching, parsing, pagination, and rate limiting in one async function:
async fn crawl(client: Client, mut url: String) -> Vec<String> {
let title = Selector::parse("h3 a").unwrap();
let next = Selector::parse("li.next a").unwrap();
let mut titles = Vec::new();
loop {
let body = client.get(&url).send().await.unwrap().text().await.unwrap();
let doc = Html::parse_document(&body);
titles.extend(doc.select(&title).filter_map(|a| a.attr("title")).map(String::from));
match doc.select(&next).next().and_then(|a| a.attr("href")) {
Some(href) => url = format!("https://books.toscrape.com/catalogue/{href}"),
None => break,
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
titles
}
Awaiting that function directly from main works. Passing it to tokio::spawn(crawl(client, start)) fails to compile with rustc 1.100:
error: future cannot be sent between threads safely
|
= help: within `tendril::tendril::NonAtomic`, the trait `Sync` is not implemented for `Cell<usize>`
note: future is not `Send` as this value is used across an await
|
11 | let doc = Html::parse_document(&body);
| --- has type `Html` which is not `Send`
...
19 | tokio::time::sleep(std::time::Duration::from_millis(500)).await;
| ^^^^^ await occurs here, with `doc` maybe used later
The constraint comes from values retained across an .await:
scraper::Htmlstores text using tendrils. By default, those use non-atomic reference counting backed byCell<usize>, makingHtmlnon-Send.- In this function,
docremains live acrosssleep(...).await, so the suspended future retains a non-Sendvalue. tokio::spawnrequires aSendfuture because a spawned task may resume on another worker thread.
You have three options:
- Return owned data from a synchronous parser. Create and drop
Htmlinsideparse_listing. Only the extractedStrings andUrls remain when the caller reaches its next.await. Use this as the default boundary between parsing and network work. - End the parser’s scope before awaiting. Put the document and all operations that borrow it inside a block that ends before
sleep. This works, but adding an.awaitinside that block can reintroduce the same error. - Enable scraper’s
atomicfeature. Withscraper = { version = "0.29", features = ["atomic"] }, the demonstrated function compiles because text uses atomic tendrils. The tradeoff is conversion to the thread-safe representation during parsing.
The synchronous parser is also easier to test. Pass in saved HTML and check the extracted records without starting tokio or making network requests.
Crawl Listings, Then Fetch Details Four at a Time
Fetch listing pages sequentially because each response supplies the next page’s URL. Once you have the product URLs, fetch their detail pages concurrently to extract the UPC and stock count:
static UPC: LazyLock<Selector> = LazyLock::new(|| sel("table.table-striped tr:first-child td"));
static AVAILABILITY: LazyLock<Selector> = LazyLock::new(|| sel("p.availability"));
#[derive(Debug)]
struct Detail {
upc: String,
stock: u32,
}
fn parse_detail(body: &str) -> Option<Detail> {
let doc = Html::parse_document(body);
let upc = text_of(doc.select(&UPC).next()?);
// "In stock (22 available)" -> 22
let stock = text_of(doc.select(&AVAILABILITY).next()?)
.chars()
.filter(char::is_ascii_digit)
.collect::<String>()
.parse()
.unwrap_or(0);
Some(Detail { upc, stock })
}
async fn get_html(client: &Client, url: &Url) -> Result<String, BoxError> {
for attempt in 0..3 {
let resp = client.get(url.clone()).send().await?;
if resp.status() != StatusCode::TOO_MANY_REQUESTS {
return Ok(resp.error_for_status()?.text().await?);
}
// Retry-After in seconds if the site sends it, else 2, 4, 8 s
let wait = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok())
.unwrap_or(2u64 << attempt);
tokio::time::sleep(Duration::from_secs(wait)).await;
}
Err(format!("still rate limited after 3 tries: {url}").into())
}
#[tokio::main]
async fn main() -> Result<(), BoxError> {
let client = Client::builder()
.user_agent("books-scraper/0.1 (+mailto:you@example.com)")
.timeout(Duration::from_secs(30))
.build()?;
// 1. Walk the listing pages in order, one at a time.
let mut next = Some(Url::parse("https://books.toscrape.com/catalogue/page-1.html")?);
let mut books = Vec::new();
while let Some(url) = next.take() {
let body = get_html(&client, &url).await?;
let (found, next_page) = parse_listing(&body, &url);
books.extend(found);
next = next_page;
if books.len() >= 40 {
break;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
// 2. Fetch the product pages, at most 4 at a time.
let results: Vec<(Book, Option<Detail>)> = stream::iter(books)
.map(|book| {
let client = client.clone();
async move {
let detail = match get_html(&client, &book.url).await {
Ok(body) => parse_detail(&body),
Err(e) => {
eprintln!("{e}");
None
}
};
(book, detail)
}
})
.buffer_unordered(4)
.collect()
.await;
for (book, detail) in results.iter().take(3) {
if let Some(d) = detail {
println!("{} | {} | UPC {} | {} in stock", book.title, book.price, d.upc, d.stock);
}
}
println!("{} books", results.len());
Ok(())
}
The recorded debug-build run fetched 40 books in under four seconds:
Soumission | £50.10 | UPC 6957f44c3847a760 | 20 in stock
Tipping the Velvet | £53.74 | UPC 90fa61229261140a | 20 in stock
A Light in the Attic | £51.77 | UPC a897fe39b1053632 | 22 in stock
40 books
“A Light in the Attic” is first on the listing page but third in the output. buffer_unordered(4) emits results in completion order. If you need input order, use .buffered(4), with the tradeoff that a slow earlier request delays delivery of later results.
The limit of 4 controls concurrent detail-fetch futures, not an exact number of TCP connections. Connection pooling and the negotiated HTTP version determine how requests use connections. Start with low concurrency on a real target and increase it only while responses remain healthy.
The get_html function also retries HTTP 429 responses. It honors Retry-After when the value is a delay in seconds. It does not parse the alternative HTTP-date form; in that case, it falls back to delays of 2, 4, and 8 seconds. See the retry logic guide for retry patterns that avoid repeatedly hitting an already-limited endpoint.
Wall 3: A Browser User-Agent Does Not Fix Every 403
Point the same client at an Etsy category page. Replacing the User-Agent with a full Chrome string still produces a block:
403 Forbidden
server: DataDome
x-datadome: protected
The recorded response contains 776 bytes of HTML that loads a challenge from captcha-delivery.com.
Changing .user_agent(...) changes an HTTP header. It does not change the TLS ClientHello sent by rustls or the client’s HTTP/2 settings to match Chrome. Those protocol-level characteristics can distinguish the client from the browser it claims to be. The TLS fingerprinting guide explains the handshake signals.
The response also requires JavaScript, which scraper does not execute. Matching a handshake would not, by itself, solve that challenge.
Detect the Challenge Before Choosing a Fallback
Do not treat the presence of x-datadome as proof of a block. Etsy also sends x-datadome: protected on normal HTTP 200 pages. That header identifies protection, not the outcome of a particular request.
For the DataDome block response shown here, the server header identifies DataDome. For Cloudflare challenge pages, the documented response marker is cf-mitigated: challenge.
Use the status and these response headers to identify the cases handled by this example:
use reqwest::Response;
fn looks_blocked(resp: &Response) -> bool {
let header_is = |name: &str, value: &str| {
resp.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.eq_ignore_ascii_case(value))
};
header_is("cf-mitigated", "challenge") // Cloudflare challenge page
|| header_is("server", "DataDome") // DataDome answered, not the site
|| resp.status() == StatusCode::FORBIDDEN
}
These checks are not exhaustive. A server can return HTTP 200 with challenge HTML instead of the requested content. The guide to HTTP 200 responses that are actually blocks covers body markers you can check as well.
Choose a Client That Handles the Actual Failure
Once you have identified a block, choose a fallback based on what the request needs:
- Emulate a browser’s protocol fingerprint with wreq. It offers a reqwest-style interface and browser emulation profiles through
wreq-util, covering TLS and HTTP/2 characteristics associated with fingerprints such as JA3 and JA4. It builds BoringSSL from source and requires CMake, Perl, and a C toolchain. It does not execute JavaScript, so a JavaScript challenge remains a separate problem. - Drive a browser. chromiumoxide uses the Chrome DevTools Protocol. fantoccini and thirtyfour use WebDriver. Budget for browser processes consuming hundreds of megabytes of RAM and page loads taking seconds. Browser automation can also expose detection signals, as the Playwright vs real Chrome post explains.
- Route blocked URLs through a scraping API. Keep reqwest for pages it can fetch directly, and use the fallback only when your block checks trigger.
Fall Back to an API Only for Blocked URLs
The API approach can keep the same parsing boundary. Your fetch layer returns an HTML String whether it obtains the page directly or through ScrapeUnblocker.
The official scrapeunblocker crate is an async tokio client; the version used here is 0.22.0. Add it with cargo add scrapeunblocker, set SCRAPEUNBLOCKER_KEY, and use the block detector to decide when to invoke it:
async fn fetch_with_fallback(
client: &Client,
su: &scrapeunblocker::Client,
url: &Url,
) -> Result<String, BoxError> {
let resp = client.get(url.clone()).send().await?;
if !looks_blocked(&resp) {
return Ok(resp.error_for_status()?.text().await?);
}
eprintln!("{} from {url}, retrying through the API", resp.status());
Ok(su.get_page_source(url.as_str()).await?)
}
// let su = scrapeunblocker::Client::from_env()?; // reads SCRAPEUNBLOCKER_KEY
In the recorded test, reqwest fetched the books page directly. The Etsy category request used the API fallback and returned about 1 MB of HTML.
Your parser still receives a String, so it does not need a separate API-specific implementation. Direct requests do not consume paid API requests; only URLs sent through the fallback do.
FAQ
Is Rust faster than Python for web scraping?
For a few hundred pages a day, network waiting usually dominates, so you are unlikely to notice a language-level difference. Rust becomes more relevant when parsing large pages is the bottleneck or when thousands of concurrent tasks make memory per task significant.
Can scraper run JavaScript?
No. It parses the HTML returned by the server without executing scripts. For pages populated by JavaScript, inspect the JSON API used by the page, as described in how to find the hidden JSON API, or drive a browser with chromiumoxide.
How do I keep cookies between requests with reqwest?
Enable the cookies feature with cargo add reqwest --features cookies, then call .cookie_store(true) on the ClientBuilder. Clones of that client share the same cookie jar.
Can I use reqwest without async?
Yes. Enable the blocking feature and use reqwest::blocking::Client for synchronous scripts. Do not call it from inside a tokio runtime: it panics when it tries to block the runtime thread.
Run It Against Your Own Target
Verify the crawler on books.toscrape.com before changing the target. Then fetch one representative URL from your target and inspect its status, server and cf-mitigated headers, and response body. Confirm that the body contains the expected content before expanding the crawl. Missing challenge headers alone do not establish that a request succeeded.
If you choose ScrapeUnblocker for blocked requests, the Rust SDK docs cover Markdown output, browser steps, sticky sessions, and typed errors. Set up a key at app.scrapeunblocker.com, then test the fallback on a known blocked URL before using it across the crawl.
Try ScrapeUnblocker free
95%+ success rate · from 0.55€ per 1,000 calls (VAT may apply) · 500 free requests on signup.