Extracting resources | rust-crawler | Spatie       

 SPATIE  

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

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Configuring-the-crawler  Extracting resources

 Version   v1      

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

  Extracting resources    
- [ 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)

 Extracting resources
====================

###  On this page 

1. [ Extracting specific resource types ](#content-extracting-specific-resource-types)
2. [ Resource types and discovery information ](#content-resource-types-and-discovery-information)
3. [ Base URLs and sitemaps ](#content-base-urls-and-sitemaps)
4. [ Metadata and Markdown ](#content-metadata-and-markdown)

`HtmlExtractor::default()` discovers page links and metadata. Configure it separately from the crawler, then pass it to `.extractor(...)`. Markdown and asset discovery are opt-in.

Link and metadata extraction normally reads HTML without building a full DOM tree. Recognized markup that needs HTML5 tree repair uses the DOM parser instead, as does Markdown conversion. Both paths use the same URL validation, resource classification and metadata rules. The original response body remains available on the page; this optimization does not stream network bodies or enqueue links before the response has been processed.

Extracting specific resource types
--------------------------------------------------------------------------------------------------------------------------------------------------------------

```
use spatie_crawler::{Crawler, HtmlExtractor, ResourceType};

fn asset_crawler() -> spatie_crawler::Result {
    let extractor = HtmlExtractor::default()
        .also_extract(ResourceType::Image)
        .also_extract(ResourceType::Stylesheet);

    Crawler::builder("https://example.com")?
        .extractor(extractor)
        .build()
}
```

TypeSources`ResourceType::Link```, ``, next/previous links, hreflang links, and alternate HTML links; always enabled`ResourceType::Image``` and ```ResourceType::Script``` and ```ResourceType::Stylesheet`Links with `rel="stylesheet"`, `type="text/css"`, or `as="style"``ResourceType::OpenGraphImage`Supported `og:image`, `og:image:url`, `og:image:secure_url`, `twitter:image`, and `twitter:image:src` meta properties or names`ResourceType::Sitemap`Child sitemap locations in supported XML sitemap indexes`HtmlExtractor::default().extract_all()` enables all optional HTML asset types. It does not discover every possible browser subresource, such as CSS imports or image `srcset` candidates.

Discovered assets enter the same frontier as pages. They share host scope, deduplication, robots checks and [crawl limits](setting-crawl-limits). Assets on a CDN may be outside the default same-host scope. Enabling asset discovery does not bypass [MIME filtering](handling-responses).

Resource types and discovery information
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

`page.discovered.resource_type` describes the URL's first discovery. `page.document.links` contains the resources extracted from that response. The store deduplicates by URL identity, so a URL found as multiple resource types is not fetched once per type.

```
use spatie_crawler::{CrawlEvent, Crawler, HtmlExtractor};

#[tokio::main]
async fn main() -> Result {
    let mut crawl = Crawler::builder("https://example.com")?
        .extractor(HtmlExtractor::default().extract_all())
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        match event {
            CrawlEvent::Page { page, .. } => {
                println!("{:?}: {}", page.discovered.resource_type, page.url);
                if let Some(parent) = &page.discovered.found_on {
                    println!("Found on {parent}");
                }
            }
            CrawlEvent::Failed { url, response, error, .. } => {
                if let Some(response) = response {
                    eprintln!("{:?}: {} returned {}", url.resource_type, url.url, response.status);
                } else {
                    eprintln!("{}: {error}", url.url);
                }
            }
            CrawlEvent::MalformedUrl { url, found_on, resource_type, link_text, error, .. } => {
                eprintln!("Malformed {resource_type:?} reference {url} on {found_on}: {error}");
                eprintln!("Link text: {link_text:?}");
            }
            CrawlEvent::Finished { error: Some(error), .. } => return Err(error.into()),
            _ => {}
        }
    }
    Ok(())
}
```

HTTP failures such as broken-image 404s produce `Failed`, not `Page`. Their `response` retains the HTTP status and body; transport failures have no response. Malformed references are separate events, not failed network requests, and do not suppress the containing page. Non-HTTP references are not crawl targets.

`document.malformed_links` contains `MalformedLink` records with the raw `url`, parsing `error`, typed `resource_type` and optional `link_text`. `MalformedUrl` events carry the same fields plus the containing page's final URL as `found_on`. Like valid discoveries within a document, malformed references deduplicate by URL and resource type, keeping the first link text. The same invalid spelling used by an anchor and an image produces two records, while repeated image references produce one. Only enabled resource types are reported. Anchor text uses the same whitespace normalization and 512-character bound as valid links; resources have no link text.

Malformed references increment `Progress::malformed`, not network attempts or failed fetches, and are never enqueued. With robots handling enabled, document-level nofollow suppresses their events. Older serialized malformed records without provenance deserialize as `ResourceType::Link` with no text.

Base URLs and sitemaps
--------------------------------------------------------------------------------------------------------------------------

Relative links and resource URLs resolve against the page's final URL, or its valid `` when present. The default extractor parses HTML, XHTML and supported XML sitemaps. Sitemap URL sets expose page locations; sitemap indexes expose child sitemap locations. Other response types produce an empty `Document` unless you provide a custom extractor. Text is decoded as lossy UTF-8, without charset detection.

`discover_sitemaps(true)` also queues robots.txt `Sitemap` declarations and `/sitemap.xml`. Missing sitemap probes are skips. `map_only(true)` fetches the primary root and sitemap documents but emits `Discovered` for target URLs without downloading those pages. Discovery alone does not establish reachability or indexability.

Metadata and Markdown
-----------------------------------------------------------------------------------------------------------------------

Metadata is extracted independently of Markdown selection. `page.document.metadata` includes optional title, description, language and canonical URL, plus an `open_graph` map with a vector of values for each property. Repeated Open Graph values are preserved. `document.title` and `document.description` also expose the title and description directly.

```
use spatie_crawler::{Crawler, HtmlExtractor, Page};

fn content_crawler() -> spatie_crawler::Result {
    let extractor = HtmlExtractor::default()
        .markdown(true)
        .only_main_content(true)
        .include_selector("main, article")?
        .exclude_selector(".advertisement")?;

    Crawler::builder("https://example.com")?
        .extractor(extractor)
        .build()
}

fn print_content(page: &Page) {
    println!("Title: {:?}", page.document.metadata.title);
    println!("Canonical: {:?}", page.document.metadata.canonical);
    if let Some(markdown) = &page.document.markdown {
        println!("{markdown}");
    }
}
```

Markdown appears in `page.document.markdown` only when enabled. `only_main_content(true)` removes common navigation and surrounding elements and prefers main/article containers, falling back to the body. This is selector-based extraction, not an AI service.

Include selectors choose Markdown roots. Exclude selectors remove matching elements. Repeated selectors form unions, and invalid selectors return configuration errors. These selectors affect Markdown only; they do not narrow link discovery or metadata. Links outside the selected content can still be crawled. See [robots handling](respecting-robots-txt) for link-level and document-level nofollow behavior.

 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)
