Rust Web Scraping With reqwest and scraper: Measured
Rust web scraping from zero to CSV: debug vs release parse speed, reqwest's missing User-Agent, and the JavaScript wall. Every number measured.

On this page
Rust web scraping has a price list: 32 seconds of compile time before your first HTTP request. The payoff, on this machine: a parser that chews through a page in 0.4 milliseconds, about half of Nokogiri’s 0.76 on the same HTML. Everything below ran on Rust 1.99.1 against quotes.toscrape.com, the scraping sandbox, and every number is measured.
The stack: five crates, versions verified today
| Crate | Version | Total downloads | License | Job |
|---|---|---|---|---|
| reqwest | 0.13.5 | 864M | MIT OR Apache-2.0 | HTTP client |
| tokio | 1.54.1 | 1.14B | MIT | Async runtime reqwest sits on |
| scraper | 0.29.0 | 35M | ISC | CSS selectors over Servo’s html5ever |
| csv | 1.4.0 | 281M | Unlicense OR MIT | CSV output |
| serde_json | 1.0.154 | 1.54B | MIT OR Apache-2.0 | JSON API pulls in Step 4 |
Numbers from crates.io API on 2026-11-02. One churn warning before you copy Cargo.toml lines from older tutorials: these are 0.x crates, and reqwest 0.13 renamed its TLS features. --features rustls-tls, the line every 2023-era guide ships, now fails with error: unrecognized feature (I ran that exact error today). In 0.13, rustls is the default TLS stack, which is good news: no OpenSSL headers to install on any platform.
Before you start
You need rustup (curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh) and nothing else. Everything here ran on Rust 1.99.1 (2026-10-13), the current stable, on a 16-core Linux box over a home connection.
cargo new scrape && cd scrape
cargo add reqwest --features json
cargo add tokio --features macros,rt-multi-thread
cargo add scraper csv serde_json
cargo build
That resolves 210 crates into Cargo.lock and compiles in 31.9 seconds cold, 51.3 seconds for the optimized release build, and 1.9 seconds for every edit after that. The compile tax is per dependency change, not per keystroke.
Each program below lives in src/bin/ and runs standalone with cargo run --bin <name>, so you can pull one step at a time without touching the others.
Step 1: Fetch a page (and set a User-Agent, because reqwest sends none)
// src/bin/fetch.rs
use std::time::Instant;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let t0 = Instant::now();
let html = reqwest::get("https://quotes.toscrape.com/").await?.text().await?;
println!("{} bytes, {} ms", html.len(), t0.elapsed().as_millis());
Ok(())
}
11064 bytes, 1110 ms
That 1,110 ms includes the cold TLS handshake; repeat runs land well under it. The byte count matches what the Ruby and Go runs on this box measured against the same page, which is the point of a sandbox: identical input, so the only variable is your code.
reqwest::get is a convenience that builds a throwaway client per call. Fine for one page, wasteful for a crawl; Step 3 builds one Client and reuses it.
Three failure modes to fix before they fix you:
reqwest sends no User-Agent header. Nothing. Ruby’s open-uri at least says Ruby; reqwest says nothing at all. Pointed at httpbin.org, the echoed headers are exactly two:
// src/bin/ua.rs
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let body = reqwest::get("https://httpbin.org/get").await?.text().await?;
println!("{}", &body[..600.min(body.len())]);
Ok(())
}
{
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org"
},
"method": "GET",
"origin": "27.130.86.101",
"url": "https://httpbin.org/get"
}
Plenty of CDNs treat a missing User-Agent as bot traffic on sight. The fix is one builder line: Client::builder().user_agent("QuoteBot/1.0 (+mailto:[email protected])").
HTTP errors don’t raise. A 404 comes back as a perfectly valid Response with a status field. If you don’t check, your parser runs against the error page and your database fills with nothing.
// src/bin/notfound.rs
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let res = reqwest::get("https://quotes.toscrape.com/no-such-page/").await?;
println!("status: {}", res.status());
match res.error_for_status() {
Ok(_) => println!("ok"),
Err(e) => println!("error_for_status: {e}"),
}
Ok(())
}
status: 404 Not Found
error_for_status: HTTP status client error (404 Not Found) for url (https://quotes.toscrape.com/no-such-page/)
No default timeout. A server that accepts the connection and never answers will hang your scraper indefinitely. Set Client::builder().timeout(Duration::from_secs(30)) and stop thinking about it. Step 3 does both in one builder.
Step 2: Select with scraper, and always benchmark in release
// src/bin/parse.rs
use std::time::Instant;
use scraper::{Html, Selector};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let html = reqwest::get("https://quotes.toscrape.com/").await?.text().await?;
let runs = 100;
let t0 = Instant::now();
let mut quotes = 0;
for _ in 0..runs {
let doc = Html::parse_document(&html);
quotes = doc.select(&Selector::parse("div.quote").unwrap()).count();
}
let per = t0.elapsed().as_secs_f64() * 1000.0 / runs as f64;
println!("{quotes} quotes, {per:.3} ms per parse+select over {runs} runs");
Ok(())
}
In a debug build, that prints 10 quotes, 6.186 ms per parse+select over 100 runs — slower than Ruby. Then you run it in release and the same file prints 0.406 ms, with the binary shrinking from 4.5 MB to 445 KB while you’re at it. A 15× gap. Every Rust speed claim you’ve read assumes release builds, and this is why: debug html5ever is a different animal. For any scraping you’ll run more than once, cargo build --release is the honest build.
Under the hood, scraper wraps html5ever 0.40.1, the HTML5 parser from the Servo project (spec-grade parsing, not string munging).
// src/bin/select.rs
use scraper::{Html, Selector};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let html = reqwest::get("https://quotes.toscrape.com/").await?.text().await?;
let doc = Html::parse_document(&html);
let quote = Selector::parse("div.quote").unwrap();
let text = Selector::parse("span.text").unwrap();
let author = Selector::parse("small.author").unwrap();
let tag = Selector::parse("a.tag").unwrap();
for q in doc.select("e).take(2) {
let t = q.select(&text).next().unwrap().text().collect::<String>();
let a = q.select(&author).next().unwrap().text().collect::<String>();
let tags = q.select(&tag).map(|t| t.text().collect::<String>()).collect::<Vec<_>>();
println!("{a}: {t} {tags:?}");
}
println!("quotes on page: {}", doc.select("e).count());
Ok(())
}
Albert Einstein: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.” ["change", "deep-thoughts", "thinking", "world"]
J.K. Rowling: “It is our choices, Harry, that show what we truly are, far more than our abilities.” ["abilities", "choices"]
quotes on page: 10
The curly quotes survive because everything is UTF-8 end to end. And that .text().collect::<String>() chorus is not ceremony: scraper’s .text() returns an iterator of text fragments, one per text node between tags. Element <p>a<b>c</b></p> yields "a", "c". Collect or lose your middle words. It’s the single most common scraper-crate mistake.
Three more failure modes, all measured:
A typo’d selector fails at parse time, loudly:
// src/bin/badsel.rs
use scraper::{Html, Selector};
fn main() {
match Selector::parse("div.quote[") {
Ok(_) => println!("parsed"),
Err(e) => println!("Selector::parse error: {e}"),
}
let html = r#"<html><body><p>hi</p></body></html>"#;
let doc = Html::parse_document(html);
let typo = Selector::parse("div.quote").unwrap();
println!("match on wrong page: {} elements", doc.select(&typo).count());
}
Selector::parse error: Unexpected EOL
match on wrong page: 0 elements
Two lessons in that output. First, invalid selectors are runtime errors, not compile errors. If your selectors come from a config file, parse them all at startup and fail before the first request. Second, a valid selector that matches nothing is a silent empty iterator, the Rust twin of Ruby’s nil. Count records every run; a number that suddenly drops is your redesign alarm.
Step 3: Crawl the pagination into a CSV
// src/bin/crawl.rs
use std::time::{Duration, Instant};
use scraper::{Html, Selector};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let t0 = Instant::now();
let client = reqwest::Client::builder()
.user_agent("QuoteBot/1.0 (+mailto:[email protected])")
.timeout(Duration::from_secs(30))
.build()?;
let next = Selector::parse("li.next a").unwrap();
let quote = Selector::parse("div.quote").unwrap();
let text = Selector::parse("span.text").unwrap();
let author = Selector::parse("small.author").unwrap();
let tag = Selector::parse("a.tag").unwrap();
let mut url: reqwest::Url = "https://quotes.toscrape.com/".parse()?;
let mut w = csv::Writer::from_path("quotes.csv")?;
let mut rows = 0;
loop {
let html = client.get(url.clone()).send().await?.text().await?;
let doc = Html::parse_document(&html);
for q in doc.select("e) {
w.write_record(&[
q.select(&text).next().map(|t| t.text().collect::<String>()).unwrap_or_default(),
q.select(&author).next().map(|a| a.text().collect::<String>()).unwrap_or_default(),
q.select(&tag).map(|t| t.text().collect::<String>()).collect::<Vec<_>>().join("|"),
url.to_string(),
])?;
rows += 1;
}
let Some(a) = doc.select(&next).next() else { break };
url = url.join(a.attr("href").ok_or("next link without href")?)?;
std::thread::sleep(Duration::from_millis(500));
}
w.flush()?;
let ms = t0.elapsed().as_millis();
println!("{rows} quotes from the sandbox in {ms} ms");
Ok(())
}
100 quotes from the sandbox in 8796 ms
Ten pages, 100 quotes, one CSV. The 8.8 s breaks down as 4.5 s of deliberate sleep and about 0.43 s per page for fetch plus that 0.4 ms parse. The identical Ruby loop took 16.1 s on this connection this morning; the difference is mostly the HTTP layer, since reqwest’s Client pools connections across pages while Ruby’s open-uri re-negotiated TLS for every request. Network variance being what it is, treat the gap as directional, not a benchmark.
Mechanics worth naming. url.join() handles the sandbox’s root-relative href="/page/2/" (reqwest re-exports the url crate’s Url type), and join is the URL-resolution logic people hand-roll wrong. And one honest compile story: my first draft passed a &str into a row of Strings, and the compiler refused the build with error[E0308] plus a one-line suggestion. Thirty seconds lost, zero silently mis-typed rows shipped. That’s the Rust trade in miniature.
Politeness: the 0.5-second sleep is the entire throttle. The sandbox ships no robots.txt (it’s a 404), but real targets set Crawl-delay lines and mean them. The mechanics live in our rate limiting glossary entry.
Step 4: The JavaScript wall, and the door next to it
The sandbox ships two JavaScript variants of the same quotes page. Static fetching gets nothing from either:
// src/bin/js.rs
use scraper::{Html, Selector};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
for path in ["/js/", "/scroll"] {
let html = reqwest::get(format!("https://quotes.toscrape.com{path}")).await?.text().await?;
let doc = Html::parse_document(&html);
let q = Selector::parse("div.quote").unwrap();
let s = Selector::parse("script").unwrap();
println!("{path}: {} div.quote, {} script tags, mentions api/quotes: {}",
doc.select(&q).count(), doc.select(&s).count(), html.contains("api/quotes"));
}
Ok(())
}
/js/: 0 div.quote, 2 script tags, mentions api/quotes: false
/scroll: 0 div.quote, 2 script tags, mentions api/quotes: true
html5ever never executes scripts, so /js/ keeps its quotes inside an inline var data = [...] blob, one regex away for this page, a sandbox luxury you shouldn’t learn to rely on. The /scroll page is more instructive: its script fetches api/quotes?page=N from the same origin, no auth, clean JSON. So skip the browser and read the API directly:
// src/bin/api.rs
use serde_json::Value;
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut page = 1;
let mut total = 0;
loop {
let v: Value = reqwest::get(format!("https://quotes.toscrape.com/api/quotes?page={page}"))
.await?
.json()
.await?;
total += v["quotes"].as_array().map(|a| a.len()).unwrap_or(0);
if v["has_next"].as_bool() != Some(true) {
break;
}
page += 1;
std::thread::sleep(Duration::from_millis(500));
}
println!("{total} quotes from {page} API pages, zero HTML parsing");
Ok(())
}
100 quotes from 10 API pages, zero HTML parsing
That’s the transferable skill: open the browser’s network tab before reaching for a headless browser. The limit is equally real: production sites hide their endpoints behind authentication, request signing, or pagination schemes built to resist exactly this. When there is genuinely no API, the Rust options are headless_chrome 1.0.22, chromiumoxide 0.9.1, or fantoccini 0.22.1 (versions verified on crates.io today), all of which drive a real Chrome and pay seconds per render instead of 0.4 ms. What that buys and what it still misses is covered in JavaScript rendering and the dynamic websites guide. For whole-site crawls rather than page loops, the spider crate (2.53.9, MIT, 2.1M downloads) is the Rust-native entry point.
A different shape of tool, for the record: Magpie (Go, AGPL-3.0-or-later or commercial license) does the same static-first fetch, escalates to a real browser only when a page needs JavaScript, and keeps a per-domain selector cache that re-synthesizes selectors after a site redesign. It’s a standalone binary, not a library; you configure it instead of compiling it. Keep it in mind for scrapes where maintaining Rust selectors isn’t the job.
What breaks outside the sandbox
The TLS fingerprint wall. rustls completes handshakes all day, but its client-hello shape doesn’t sound like Chrome, and sites that score handshakes will reject it no matter what headers you send. No mainstream Rust crate impersonates a browser’s handshake. The realistic answers are an impersonating proxy in front of your client or a real browser, and those are different budget lines. The Go and Ruby siblings of this tutorial hit the same wall, and so does Node: every language’s static stack ends in the same place.
Selector rot stays silent. Step 2’s empty iterator compounds across a crawl: a redesign turns 100 rows into 0 with no exception anywhere. Print the record count every run and alert on the drop.
The compile tax returns on dependency changes. Python imports its scraping stack in zero seconds; Rust recompiles when Cargo.toml changes, and reqwest’s tree is not small. After the first 32 seconds here, code edits rebuilt in 1.9 s, which is a normal edit-run loop. Budget the seconds for the days you add crates, not for the days you write code.
FAQ
Is Rust good for web scraping?
For parse-heavy scraping, yes: 0.406 ms per page in release, a 445 KB binary, no garbage collector pausing mid-crawl. The costs are compile time and a stricter error model. For light scraping, Python and Node iterate faster and hit the same JavaScript wall anyway.
Why is my Rust scraper so slow?
You’re benchmarking a debug build. Debug parsed at 6.19 ms per page here; release did 0.406 ms. A 15× gap. Run cargo build --release for anything that touches real data volume.
Does the scraper crate render JavaScript?
No. It parses markup; scripts stay inert text. Check for a same-origin JSON API first (Step 4 found one in minutes), then reach for headless Chrome via a crate if there’s truly no endpoint.
scraper or select?
scraper. It wraps Servo’s html5ever and shipped 0.29.0 on 2026-10-21; select’s last release was March 2025. Registry facts checked today; the maintained default is the safer bet.
Is web scraping with Rust legal?
Same as any language: scraping public data is generally lawful; login-walled data, copyright, and terms-of-service violations are where courts have ruled both ways. Check robots.txt, throttle yourself, skip personal data. Not legal advice.
Where this goes next
The sandbox has a login form at /login, which is the natural next exercise: reqwest handles the POST with .form(&[("username", "…"), ("password", "…")]) and keeps the session alive with Client::builder().cookie_store(true) (enable its cookies feature). Beyond it, the Node.js and Go versions of this tutorial end at the same walls — the language changes, the JavaScript wall doesn’t. Learn the pattern here, where a missed selector costs you a 1.9-second rebuild instead of a production incident.


