Crawl responses | rust-crawler | Spatie       

 SPATIE  

rust-crawler
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Basic-usage  Crawl responses

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/rust-crawler/v1) 

  Crawl responses    
- [ Introduction ](https://spatie.be/docs/rust-crawler/v1/introduction)
- [ Installation &amp; setup ](https://spatie.be/docs/rust-crawler/v1/installation-setup)
- [ Support us ](https://spatie.be/docs/rust-crawler/v1/support-us)
- [ Questions and issues ](https://spatie.be/docs/rust-crawler/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/rust-crawler/v1/changelog)
- [ About us ](https://spatie.be/docs/rust-crawler/v1/about-us)

Basic usage
-----------

- [ Your first crawl ](https://spatie.be/docs/rust-crawler/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/rust-crawler/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/rust-crawler/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/rust-crawler/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/rust-crawler/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/respecting-robots-txt)

Advanced usage
--------------

- [ JavaScript rendering ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/graceful-shutdown)

 Crawl responses
===============

###  On this page 

1. [ Bodies and headers ](#content-bodies-and-headers)
2. [ Querying the DOM ](#content-querying-the-dom)
3. [ HTTP and transport failures ](#content-http-and-transport-failures)
4. [ Redirects ](#content-redirects)
5. [ Timings and statistics ](#content-timings-and-statistics)

`CrawlEvent::Page` contains a boxed `Page`. Its public fields hold the original `url`, `final_url`, HTTP `status`, `headers`, `body`, redirect history, discovery metadata, extracted `document`, attempt count, stage timings and transport statistics.

```
use spatie_crawler::Page;

fn inspect(page: &Page) {
    println!("{} -> {} ({})", page.url, page.final_url, page.status);
    println!("{} bytes, {} attempts", page.body.len(), page.attempts);
    println!("Title: {:?}", page.document.metadata.title);
    println!("Found on: {:?}", page.discovered.found_on);
    println!("Link text: {:?}", page.discovered.link_text);
    println!("Depth: {}, type: {:?}", page.discovered.depth, page.discovered.resource_type);
    if let Some(value) = page.headers.get("content-type") {
        println!("Content-Type: {value:?}");
    }
}
```

Bodies and headers
--------------------------------------------------------------------------------------------------------------

`body` is `bytes::Bytes`. Cloning it shares the allocation rather than copying the whole response. `page.text()` returns borrowed text for valid UTF-8 and replaces invalid sequences when needed. It does not apply the HTTP charset to decode other encodings. Keep the original bytes when encoding matters.

Headers use reqwest's `HeaderMap`. Use `get_all` for repeated values and `to_str()` only when a value is valid header text. JSON serialization preserves repeated and non-text headers. Body JSON is a string for valid UTF-8, or an object with a `base64` field otherwise.

Querying the DOM
--------------------------------------------------------------------------------------------------------

`page.dom()` parses a `scraper::Html` on demand. Keep the result when making multiple queries; repeated calls parse again. Add `scraper = "0.24"` to use this example.

```
use scraper::Selector;
use spatie_crawler::Page;

fn headings(page: &Page) -> Result {
    let dom = page.dom();
    let selector = Selector::parse("h1")?;
    Ok(dom.select(&selector).map(|node| node.text().collect()).collect())
}
```

The extracted document already contains common metadata and discovered links. Use it when you do not need another DOM parse. Markdown is opt-in; see [extracting resources](../configuring-the-crawler/extracting-resources).

HTTP and transport failures
-----------------------------------------------------------------------------------------------------------------------------------------

HTTP 4xx/5xx responses are `Failed` events after applicable retries, not successful `Page` events. Their `response: Option` retains status, headers, body, redirect history and statistics. A transport error has no HTTP response. `FetchResponse` has `text()`, `dom()`, `content_type()`, `is_successful()`, `is_redirect()`, `is_client_error()`, `is_server_error()` and `was_redirected()` helpers.

```
use spatie_crawler::CrawlEvent;

fn inspect_failure(event: &CrawlEvent) {
    if let CrawlEvent::Failed { url, kind, error, response, .. } = event {
        eprintln!("{}: {kind:?}: {error}", url.url);
        if let Some(response) = response {
            eprintln!("HTTP {}, {} bytes", response.status, response.body.len());
        }
    }
}
```

`CrawlEvent::Failed::kind` and `CrawlFailure::kind` use the exported `FailureKind` enum. Branch on this field rather than matching error text:

KindMeaning`Timeout`A request/connect/body deadline or the scheduler's per-request/per-renderer timeout`Connection`Connection establishment failed, including DNS/TLS failures reported by reqwest`Http`HTTP error status; inspect `response.status``Policy`Explicit URL/network/redirect rejection, including redirect-hop limits`ResponseTooLarge`Body rejected by a byte limit`Extraction`, `Rendering`Errors reported by those stages`Configuration`, `Storage`Errors reported by extensions or per-job storage operations`Unknown`Unclassified errors, including custom `Error::Request(String)` and older serialized failuresThe HTTP transport checks reqwest's `is_timeout()` before `is_connect()` while the original error is available. A connection timeout is `Timeout`, not `Connection`. This classification does not distinguish every DNS, TCP and TLS failure. The built-in resolver's network restrictions retain a typed cause and become `Policy`, as do explicit IP-literal restrictions. No classification is inferred from diagnostic text. Custom fetchers can return `Error::Timeout`, `Error::Connection`, `Error::Policy` or other typed variants; `Error::kind()` exposes the mapping. `FakeResponse::error` remains an unclassified request error.

Request, connection and timeout failures still use the configured fetch retries, as do HTTP 429 and 5xx responses. Explicit policy and size errors do not retry. Classification describes the cause, not whether an application should report a URL as broken. Resource provenance remains in `url.resource_type`, `url.found_on` and `url.link_text`. The crawler does not suppress resource connection failures or request timeouts on an application's behalf.

Crawl-wide time budgets cancel pending work and produce `Finished { reason: FinishReason::TimeLimit, .. }`, without inventing `Failed` events for cancelled requests. Failures completed before the crawl deadline remain failures. Inspect the final event for scheduler/storage errors; not every such error is a per-URL failure.

Redirects
-----------------------------------------------------------------------------------

`page.redirects` contains redirect destinations in order, including the final destination, not the original request URL. An empty vector means no redirect. The built-in transport follows up to ten hops by default and checks each destination against crawl policy and network restrictions. Configure the limit with `HttpFetcher::builder().max_redirects(n)`. A redirect with a Location header beyond that budget is a request error; zero rejects the first such redirect rather than returning its response.

Authorization, Cookie and Proxy-Authorization headers are stripped across origins. Arbitrary custom secret headers are not. Robots rules and pacing apply to scheduled URLs, not intermediate redirect hops.

Timings and statistics
--------------------------------------------------------------------------------------------------------------------------

`page.timings` contains `fetch_ms`, `render_ms` and `extract_ms`. These describe crawler stages, not individual network phases.

`page.statistics` describes the underlying HTTP transfer. The default transport measures `total_ms`, `redirect_ms`, the final `remote_addr`, decoded `downloaded_bytes` and uploaded GET body bytes, which are zero. `download_bytes_per_second()` divides decoded body bytes by total elapsed time and returns `None` for zero elapsed milliseconds.

`dns_ms`, `connect_ms`, `tls_ms` and `ttfb_ms` are `None` because reqwest does not expose those exact phases here. They are not zero-duration measurements. Exact request-wire size is also unavailable. A custom fetcher can supply phase measurements; these fields do not promise PHP/curl timing parity. Fakes use default statistics unless a custom fetcher populates them.

Browser rendering preserves the original HTTP status and transfer statistics. Render time is separate; rendering a challenge page does not turn its original HTTP failure into success.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
