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. [ Transfer statistics ](#content-transfer-statistics)
2. [ Redirect history ](#content-redirect-history)
3. [ Using the DOM crawler ](#content-using-the-dom-crawler)
4. [ HTTP and transport failures ](#content-http-and-transport-failures)

When a URL is successfully crawled, its `Page` event contains a `Page` with the response and information about where the URL was found:

```
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:?}");
    }
}
```

`page.body` holds the response bytes. `page.text()` decodes them as UTF-8, replacing invalid sequences. It does not detect other encodings. Cloning the body shares its allocation rather than copying it.

Headers use reqwest's `HeaderMap`. Use `get_all` for repeated values. When serialized to JSON, non-UTF-8 bodies use a `base64` object instead of a string; repeated and non-text headers are preserved too.

Transfer statistics
-----------------------------------------------------------------------------------------------------------------

Each page includes transfer statistics and timings in milliseconds:

FieldMeaning`page.statistics.total_ms`Total HTTP transfer time`page.statistics.redirect_ms`Time spent on redirects`page.statistics.remote_addr`Final remote socket address, when available`page.statistics.downloaded_bytes`Decompressed bytes read from the HTTP stream`page.statistics.uploaded_bytes`GET-body bytes sent; zero with the default transport`page.timings.fetch_ms`Time spent fetching across attempts, excluding pacing and retry waits`page.timings.render_ms`Rendering duration`page.timings.extract_ms`Extraction duration`download_bytes_per_second()` divides downloaded bytes by total transfer time. It returns `None` when elapsed milliseconds are zero. Bytes read can exceed the retained body length in [prefix mode](../configuring-the-crawler/handling-responses#maximum-response-size); they are not compressed wire bytes or the original full response size.

The default reqwest transport does not expose exact DNS, TCP, TLS or first-byte phase timings. `dns_ms`, `connect_ms`, `tls_ms` and `ttfb_ms` are `None`, not zero-duration measurements. Exact request-wire size is also unavailable. A custom fetcher may supply phase timings. Fakes use default statistics.

Browser rendering preserves the original HTTP status and transfer statistics. Render time is measured separately.

Redirect history
--------------------------------------------------------------------------------------------------------

When the crawler follows redirects, `page.redirects` contains their destinations in order, including the final destination. It does not include the original request URL. An empty vector means no redirect.

The crawler follows up to 10 redirects by default. See [configuring requests](../configuring-the-crawler/configuring-requests) to change that limit and review redirect safety.

Using the DOM crawler
-----------------------------------------------------------------------------------------------------------------------

The `dom()` method returns a `scraper::Html`, which makes it easy to extract structured data from pages. 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())
}
```

Keep the returned DOM when making several queries, so you don't parse the body again. Common metadata and links are already available in `page.document`; see [extracting resources](../configuring-the-crawler/extracting-resources).

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

HTTP 4xx/5xx responses produce `Failed` events after applicable retries. Their optional `response` retains status, headers, body, redirects and statistics. Transport failures have no response:

```
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());
        }
    }
}
```

Use `FailureKind` rather than matching error text:

KindMeaning`Timeout`A request or renderer timed out, including connection and body timeouts`Connection`Connection establishment failed, including DNS/TLS errors reported by reqwest`Http`HTTP error status; inspect `response.status``Policy`URL, network or redirect rejection, including redirect-hop limits`ResponseTooLarge`Body rejected by a byte limit`Extraction`, `Rendering`Errors from those stages`Configuration`, `Storage`Extension or per-job storage errors`Unknown`Unclassified errors, including custom `Error::Request(String)` and older serialized failuresA connection timeout is `Timeout`; a blocked destination is `Policy`. Custom fetchers can return typed `Error` variants too. `FakeResponse::error` produces `Unknown`.

Failure events retain `url.found_on`, `url.link_text` and `url.resource_type`. The application decides which failures to report. Crawl-wide time limits produce `Finished` with `TimeLimit`, not failures for cancelled requests. Inspect the final event's optional `error` for scheduler or storage problems.

 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)
