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. [ Extracting all resource types ](#content-extracting-all-resource-types)
3. [ Resource types in events ](#content-resource-types-in-events)
4. [ Base href support ](#content-base-href-support)
5. [ Malformed URLs ](#content-malformed-urls)
6. [ Sitemaps ](#content-sitemaps)
7. [ Metadata and Markdown ](#content-metadata-and-markdown)

By default, the crawler only extracts links from each page, along with metadata. You can also instruct it to extract images, scripts, stylesheets, and Open Graph images. This is useful for broken asset checking, content auditing, or building an inventory of a site's resources.

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

Use the `also_extract` method to extract additional resource types alongside links. Configure `HtmlExtractor`, then pass it to `.extractor(...)`.

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

The available resource types are:

TypeWhat it extracts`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 indexesExtracting all resource types
-----------------------------------------------------------------------------------------------------------------------------------------------

To extract all supported HTML resource types at once, use `extract_all`:

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

fn all_resources() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .extractor(HtmlExtractor::default().extract_all())
        .build()
}
```

This 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 in events
--------------------------------------------------------------------------------------------------------------------------------

When handling events, the resource type is available through `page.discovered.resource_type`. It 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::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.

Base href support
-----------------------------------------------------------------------------------------------------------

When extracting links and resources, the crawler respects the `` tag in the HTML. If a page contains ``, relative resource URLs resolve against that base URL instead of the page URL. Without a valid base href, they resolve against the page's final URL.

Malformed URLs
--------------------------------------------------------------------------------------------------

When the crawler encounters a malformed URL in the HTML, it reports a `CrawlEvent::MalformedUrl` instead of silently ignoring it. The event contains the reason the URL could not be parsed.

```
use spatie_crawler::CrawlEvent;

fn report_malformed(event: &CrawlEvent) {
    if let CrawlEvent::MalformedUrl {
        url, found_on, resource_type, link_text, error, ..
    } = event {
        eprintln!("Malformed {resource_type:?} reference {url} on {found_on}: {error}");
        eprintln!("Link text: {link_text:?}");
    }
}
```

Malformed references are separate events, not failed network requests, and do not suppress the containing page. Non-HTTP references are not crawl targets.

The same references appear in `document.malformed_links`. Within a document, they deduplicate by raw URL and resource type, keeping the first link text. An anchor and image with the same invalid URL produce two records. Only enabled types are reported. Anchor text is whitespace-normalized and limited to 512 characters; 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.

Sitemaps
--------------------------------------------------------------------------------

The default extractor also parses XML sitemap URL sets and indexes. Enable `discover_sitemaps(true)` to discover sitemap locations, or combine it with `map_only(true)` to list targets without fetching them. See [crawling sitemaps](../advanced-usage/extracting-custom-links#crawling-sitemaps) for examples.

Other response types produce an empty `Document` unless you configure an [additional parsing MIME type](handling-responses#allowed-mime-types) or a custom extractor. Text is decoded as UTF-8 with invalid sequences replaced, without charset detection.

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.

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)
