Custom link extraction | rust-crawler | Spatie       

 SPATIE  

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

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Advanced-usage  Custom link extraction

 Version   v1      

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

  Custom link extraction    
- [ 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)

 Custom link extraction
======================

###  On this page 

1. [ Crawling sitemaps ](#content-crawling-sitemaps)
2. [ Mapping without fetching discovered pages ](#content-mapping-without-fetching-discovered-pages)

You can customize how links are extracted from a page by creating a type that implements `Extractor`. Its `extract` method receives the response text, final URL and content type, and returns a `Document`.

This example adds a related URL to the default extractor's results. Add `url = "2"` to your dependencies:

```
use spatie_crawler::{
    Crawler, Document, ExtractedLink, Extractor, HtmlExtractor, ResourceType,
};
use url::Url;

struct RelatedLinks {
    html: HtmlExtractor,
}

impl Extractor for RelatedLinks {
    fn extract(
        &self,
        body: &str,
        base_url: &Url,
        content_type: &str,
    ) -> spatie_crawler::Result {
        let mut document = self.html.extract(body, base_url, content_type)?;
        let mime = content_type.split(';').next().unwrap_or("").trim();
        if mime.eq_ignore_ascii_case("text/html") {
            let mut related = base_url.clone();
            related.set_path("/related");
            related.set_query(None);
            related.set_fragment(None);
            document.links.push(ExtractedLink {
                url: related,
                link_text: Some("Related pages".into()),
                resource_type: ResourceType::Link,
            });
        }
        Ok(document)
    }
}

fn custom_crawler() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .extractor(RelatedLinks {
            html: HtmlExtractor::default().markdown(true),
        })
        .build()
}
```

Each `ExtractedLink` has the following properties:

- `url`: the discovered URL.
- `link_text`: the text content of the link, if any.
- `resource_type`: `Link`, `Sitemap`, `Image`, `Script`, `Stylesheet` or `OpenGraphImage`.

Add invalid references to `Document::malformed_links` as `MalformedLink { url, error, resource_type, link_text }` rather than failing the whole page. The crawler adds parent URL and depth, then applies scope, limits, robots rules and deduplication before fetching discoveries.

By default, `HtmlExtractor` extracts page links, including next/previous and alternate links. You can also enable [resource extraction](../configuring-the-crawler/extracting-resources).

The crawler runs extraction on Tokio's blocking pool. A replacement extractor should set `may_index`, `may_follow` and `is_sitemap` for its supported formats. `Document::default()` permits indexing and following. Delegating to `HtmlExtractor` preserves metadata and HTML robots rules; the crawler applies `X-Robots-Tag` headers afterward.

Crawling sitemaps
-----------------------------------------------------------------------------------------------------------

There is a built-in option to discover sitemaps in addition to following links. It supports sitemap index files:

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

#[tokio::main]
async fn main() -> Result {
    let mut crawl = Crawler::builder("https://example.com")?
        .discover_sitemaps(true)
        .max_pages(100)
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        match event {
            CrawlEvent::Page { page, .. } => println!("{}", page.url),
            CrawlEvent::Finished { reason, error, .. } => {
                eprintln!("{reason:?}: {error:?}");
            }
            _ => {}
        }
    }
    Ok(())
}
```

This reads `Sitemap` declarations from the seed origin's robots.txt and probes `/sitemap.xml`. To start from a known sitemap, use its URL as the seed. The default extractor parses XML sitemap responses without extra setup; custom extractors need to preserve XML support.

Sitemap locations use `ResourceType::Sitemap`; page locations use `Link`. Nesting sitemaps does not increase HTML link depth. Normal scope and crawl limits apply. A 404 for a sitemap probe is a skip.

Mapping without fetching discovered pages
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Combine sitemap discovery with `map_only(true)` to fetch roots and sitemap documents, then record their target URLs without fetching those targets.

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

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

    while let Some(event) = crawl.next().await {
        match event {
            CrawlEvent::Discovered { url, .. } => println!("{}", url.url),
            CrawlEvent::Page { page, .. } if !page.document.is_sitemap => {
                println!("{}", page.url);
            }
            CrawlEvent::Finished { reason, error, .. } => {
                eprintln!("{reason:?}: {error:?}");
            }
            _ => {}
        }
    }
    Ok(())
}
```

Enable both settings: `map_only(true)` alone does not discover sitemaps. The primary seed and additional `seed_urls` are still fetched. Mapped targets count in `progress.mapped`, not successes, and remain terminal in the store. Use a fresh store for a later content crawl.

Mapping finds URLs without establishing reachability or indexability. It cannot find links inside pages it does not fetch. See [collecting URLs](../basic-usage/collecting-urls) for the CLI equivalents.

 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)
