Skip to main content
Best PracticesNovember 25, 2026 · 14 min read

Sitemap.xml vs website mapping vs crawling

Sitemap, Map or Crawl? A decision tree for finding a website's pages, with working code and real results from sites with and without a sitemap.

Sitemap.xml vs website mapping vs crawling

You need the pages of a website, but you don't know its URLs yet. On sitemap vs crawl, the short answer is this. Read the sitemap when you only need the URLs a site chooses to publish. Use Map when you need the site's URLs and the sitemap isn't enough. Use Crawl when you need the pages themselves and can describe them. This post gives you a decision tree, and shows what each method returns on real sites with code you can repeat.

What each method gives you

All three discover pages, but they answer different questions:

Sitemap.xml

Map

Crawl

Finds

The URLs the site chooses to list

URLs from the sitemap and from the site's links

Pages that match a description, found by following links

Returns

URLs, sometimes dates

URLs with the link text they were found under

Each page's content as Markdown, and extracted data if you ask

Reads page content

No

No

Yes

Cost

Free, your own requests

1 credit per map

1 credit per page returned

Read the sitemap yourself

A sitemap is a file the site publishes, so reading it is free and takes one request per file. The parser below reads the Sitemap: lines in robots.txt, falls back to /sitemap.xml and /sitemap_index.xml, follows index files and decompresses gzip. max_children caps how many child files it opens from an index. Install requests and start with the file handling:

# sitemap_urls.py
import gzip
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field

import requests

HEADERS = {"User-Agent": "sitemap-reader (research script)"}


def fetch(url):
    response = requests.get(url, headers=HEADERS, timeout=30)
    response.raise_for_status()
    body = response.content
    return gzip.decompress(body) if body[:2] == b"\x1f\x8b" else body


@dataclass
class Sitemaps:
    urls: list = field(default_factory=list)       # (url, lastmod or None)
    read: int = 0                                  # sitemap files fetched
    skipped: int = 0                               # child sitemaps left unread because of max_children
    problems: list = field(default_factory=list)   # files that failed, with the reason


def locations(site, get=fetch):
    """Sitemap files the site announces in robots.txt, else the two usual paths. Returns (urls, announced)."""
    try:
        robots = get(f"{site}/robots.txt").decode("utf-8", "replace")
        found = re.findall(r"(?im)^\s*sitemap:\s*(\S+)", robots)
    except Exception:
        found = []
    return (found, True) if found else ([f"{site}/sitemap.xml", f"{site}/sitemap_index.xml"], False)

sitemap_urls() walks the files, keeps every <loc> and records files that fail without stopping:

def sitemap_urls(site, max_children=None, get=fetch):
    """Every <loc> in the site's sitemap files, following indexes and gzip. Never raises on one bad file."""
    result, seen = Sitemaps(), set()
    queue, announced = locations(site, get)
    guesses = set() if announced else set(queue)    # a missing guess is not a problem
    children = 0
    while queue:
        url = queue.pop(0)
        if url in seen:
            continue
        seen.add(url)
        try:
            root = ET.fromstring(get(url))
        except Exception as error:
            if url not in guesses:
                result.problems.append(f"{url}: {error}")
            continue
        result.read += 1
        kind = root.tag.rsplit("}", 1)[-1]
        for node in root:
            loc = node.findtext("{*}loc")
            if not loc:
                continue
            if kind == "sitemapindex":
                if max_children is not None and children >= max_children:
                    result.skipped += 1
                else:
                    children += 1
                    queue.append(loc.strip())
            else:
                result.urls.append((loc.strip(), node.findtext("{*}lastmod")))
    if not result.read and not result.problems:
        result.problems.append("no sitemap found")
    return result

Run it on three sites. yarnpkg.com and github.com publish one file each, and pypi.org publishes an index of child files, so the run opens only the first two:

import time

from sitemap_urls import sitemap_urls

for site, children in (("https://yarnpkg.com", None), ("https://github.com", None), ("https://pypi.org", 2)):
    start = time.perf_counter()
    found = sitemap_urls(site, max_children=children)
    seconds = time.perf_counter() - start
    dated = sum(1 for _, lastmod in found.urls if lastmod)
    print(f"{site} | {len(found.urls)} URLs | {found.read} files read, {found.skipped} left unread | "
          f"{dated} with lastmod | {seconds:.1f}s | problems: {found.problems or 'none'}")

Output:

https://yarnpkg.com | 407 URLs | 1 files read, 0 left unread | 0 with lastmod | 0.6s | problems: none
https://github.com | 376 URLs | 1 files read, 0 left unread | 0 with lastmod | 0.4s | problems: none
https://pypi.org | 16237 URLs | 3 files read, 255 left unread | 0 with lastmod | 0.3s | problems: none

Each run takes under a second here. Two details matter. None of the URL entries carries a lastmod date, so you can't tell fresh pages from old ones. And pypi.org lists 255 more files than this run opened, so a full parse of that site is 258 requests: the index and its 257 files.

A sitemap can be incomplete or stale

A sitemap lists what the site chooses to list, and nothing checks that against the site. You can check it yourself by reading a sample of the sitemap's own pages and comparing the links on them with the sitemap. First, extract the same-site links from a page:

# page_links.py
from html.parser import HTMLParser
from urllib.parse import urldefrag, urljoin, urlsplit

from sitemap_urls import fetch


class Links(HTMLParser):
    def __init__(self):
        super().__init__()
        self.hrefs = []

    def handle_starttag(self, tag, attrs):
        if tag == "a" and dict(attrs).get("href"):
            self.hrefs.append(dict(attrs)["href"])


def key(url):
    parts = urlsplit(urldefrag(url)[0])
    return f"{parts.netloc.lower()}{parts.path.rstrip('/')}"


def page_links(page_url, get=fetch):
    """Same-site pages a page links to, as absolute URLs without fragments."""
    parser = Links()
    parser.feed(get(page_url).decode("utf-8", "replace"))
    host = urlsplit(page_url).netloc
    absolute = (urldefrag(urljoin(page_url, href))[0] for href in parser.hrefs)
    return sorted({u for u in absolute if urlsplit(u).scheme in ("http", "https") and urlsplit(u).netloc == host})


def not_in_sitemap(linked, sitemap_urls):
    listed = {key(url) for url, _ in sitemap_urls}
    return sorted(url for url in linked if key(url) not in listed)

Then sample 20 pages spread across the sitemap, collect their links, and note which links the sitemap doesn't list and which listed pages no longer load:

# audit.py
import time
from collections import Counter
from urllib.parse import urlsplit

import requests

from page_links import not_in_sitemap, page_links
from sitemap_urls import sitemap_urls


def audit(site, sample=20):
    """Does the sitemap list the pages the site's own pages link to, and do its pages still load?"""
    listed = sitemap_urls(site).urls
    pages = [url for url, _ in listed][::max(1, len(listed) // sample)][:sample]
    linked, unreadable = set(), []
    for page in pages:
        try:
            linked.update(page_links(page))
        except requests.RequestException as error:
            unreadable.append((page, str(error).split(" for url")[0]))
        time.sleep(0.2)
    return len(pages), len(linked), not_in_sitemap(linked, listed), unreadable


def section_of(url):
    return urlsplit(url).path.strip("/").split("/")[0] or "(home)"


def by_section(urls):
    return Counter(section_of(url) for url in urls)

Run it on the two sites that publish one file:

from audit import audit, by_section, section_of

for site in ("https://yarnpkg.com", "https://github.com"):
    pages, linked, missing, unreadable = audit(site)
    print(f"{site} | {pages} sitemap pages | {linked} distinct same-site links | "
          f"{len(missing)} not in the sitemap | {len(unreadable)} did not load")
    sections = by_section(missing)
    if sections:
        print("   not in the sitemap, by section:", ", ".join(f"{name} {count}" for name, count in sections.most_common(5)))
        for name, _ in sections.most_common()[5:8]:
            print("   example:", next(url for url in missing if section_of(url) == name))
    for url, reason in unreadable:
        print("   did not load:", url, "|", reason)

Output:

https://yarnpkg.com | 20 sitemap pages | 265 distinct same-site links | 0 not in the sitemap | 0 did not load
https://github.com | 20 sitemap pages | 265 distinct same-site links | 122 not in the sitemap | 1 did not load
   not in the sitemap, by section: organizations 20, signup 19, login 18, account 6, join 6
   example: https://github.com/solutions/ci-cd/
   example: https://github.com/resources/articles/devops/what-is-devops
   example: https://github.com/AgwambaFavour/CheckMe
   did not load: https://github.com/customer-stories/synergy | 404 Client Error: Not Found

On yarnpkg.com the sitemap and the links agree, so reading the sitemap is all you need for the URL list. On github.com the sitemap is the marketing sitemap that robots.txt announces, and it lists 376 pages of a site that has far more. Most of the 122 links it leaves out are account flows (organizations, sign-up, login), which a marketing sitemap omits on purpose. The rest are content pages, such as the solutions and resources pages in the examples, and links out to repositories. One page that the sitemap lists answers a 404. "Not in the sitemap" is not the same as "the sitemap is wrong", but it tells you whether the sitemap covers the pages you want.

The parser and audit are about 100 lines you would maintain, and they still don't help when a site publishes no sitemap at all. These tests pin the rules that are easiest to get wrong, plus a stable order for the missing links. The files in them are hand-written for testing:

# test_sitemaps.py
from page_links import not_in_sitemap
from sitemap_urls import sitemap_urls

NS = 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'


def urlset(*locs, ns=NS):
    return f'<urlset {ns}>' + "".join(f"<url><loc>{u}</loc></url>" for u in locs) + "</urlset>"


def index(*locs):
    return (f'<sitemapindex {NS}>' + "".join(f"<sitemap><loc>{u}</loc></sitemap>" for u in locs) + "</sitemapindex>").encode()


def fake(files):
    """Hand-written files for testing the parser. Not data from a real site."""
    def get(url):
        if url not in files:
            raise OSError(f"404 {url}")
        return files[url]
    return get


def test_an_index_is_followed_and_max_children_leaves_the_rest_unread():
    files = {"https://a.test/robots.txt": b"Sitemap: https://a.test/index.xml",
             "https://a.test/index.xml": index("https://a.test/1.xml", "https://a.test/2.xml", "https://a.test/3.xml"),
             "https://a.test/1.xml": urlset("https://a.test/x").encode(),
             "https://a.test/2.xml": urlset("https://a.test/y").encode()}
    found = sitemap_urls("https://a.test", max_children=2, get=fake(files))
    assert [u for u, _ in found.urls] == ["https://a.test/x", "https://a.test/y"]
    assert found.read == 3 and found.skipped == 1 and found.problems == []



def test_a_missing_guess_is_not_a_problem_but_a_missing_announced_file_is():
    guessed = sitemap_urls("https://a.test", get=fake({"https://a.test/sitemap.xml": urlset("https://a.test/x").encode()}))
    assert guessed.problems == []
    announced = sitemap_urls("https://b.test", get=fake({"https://b.test/robots.txt": b"Sitemap: https://b.test/gone.xml"}))
    assert announced.urls == [] and "gone.xml" in announced.problems[0]



def test_the_missing_links_come_back_in_a_stable_order():
    linked = {"https://a.test/z", "https://a.test/b", "https://a.test/m"}
    assert not_in_sitemap(linked, []) == ["https://a.test/b", "https://a.test/m", "https://a.test/z"]

Output:

$ pytest -q
...                                                                      [100%]
3 passed in 0.06s

Map the site

Map answers in one request. It reads the sitemap and the links on the start page and on a limited number of further pages, and it returns URLs with the link text each one was found under. It returns URLs, not page content. sitemap takes "include" (the default, sitemap and links), "only" or "skip", and search narrows the list to a topic. Install the SDK with pip install spidra (Python 3.9 or later) and put your key in SPIDRA_API_KEY. This maps books.toscrape.com, a site with no sitemap, and asks for five URLs back:

import os

from spidra import Spidra

client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
site = client.map("https://books.toscrape.com/", limit=5)
print(site.total, "URLs |", site.sources, "| credits:", site.credits_used, "|", site.duration_ms, "ms")
for link in site.links:
    print(link.url, "|", link.title)

Output:

124 URLs | {'sitemap': 0, 'pages': 124} | credits: 1 | 1765 ms
https://books.toscrape.com/ | Books to Scrape
https://books.toscrape.com/catalogue/category/books_1/index.html | Books
https://books.toscrape.com/catalogue/category/books/travel_2/index.html | Travel
https://books.toscrape.com/catalogue/category/books/mystery_3/index.html | Mystery
https://books.toscrape.com/catalogue/category/books/historical-fiction_4/index.html | Historical Fiction

total counts every URL Map found, and limit only caps how many come back. The sources split shows that all 124 came from page links and none from a sitemap. The five URLs are the home page and category pages, which are the site's structure, and the book pages sit behind those listings. A map costs 1 credit whatever the number of URLs. Asking for the sitemap alone shows what happens when there isn't one:

only = client.map("https://books.toscrape.com/", sitemap="only")
print(only.total, "URLs | credits:", only.credits_used, "|", only.message)

Output:

0 URLs | credits: 0 | This site doesn't publish a sitemap we could read. Try sitemap: "include" to read its links instead.

Nothing found costs nothing. Map can only list what the sitemap or the site's links expose, so a page with no link to it and no sitemap entry won't appear. Map is also not a walk of every listing page, so a deep catalogue needs a different tool.

Crawl for the pages themselves

Crawl starts at one URL, follows links toward the pages you describe in plain language, and returns those pages with their content. Pages it reads only to find others are navigation pages: they aren't returned and aren't charged. Here the instruction is "Individual book pages" and the crawl stops after two. A crawl runs as a job, so the code starts it and polls:

import time
from datetime import datetime

from spidra import CrawlParams

queued = client.start_crawl(CrawlParams(base_url="https://books.toscrape.com", crawl_instruction="Individual book pages", max_pages=2))
while (job := client.get_crawl(queued.job_id)).status in ("waiting", "active", "running", "delayed"):
    time.sleep(5)
if job.status != "completed":
    raise RuntimeError(f"crawl {job.status}: {getattr(job, 'error', None)}")

for page in job.result:
    print(page.url, "|", page.title)

details = client.get_crawl_job_details(queued.job_id)
report = client.crawl_report(queued.job_id).report
start, end = (datetime.fromisoformat(t.replace("Z", "+00:00")) for t in (details.created_at, details.updated_at))
print(job.total_pages, "pages |", details.credits_used, "credits |", int((end - start).total_seconds()), "s |",
      "navigation pages (free):", report.navigation_pages, "| skipped:", report.skipped_total)
print("understood as:", report.understood_as)

Output:

https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html | A Light in the Attic | Books to Scrape - Sandbox
https://books.toscrape.com/catalogue/tipping-the-velvet_999/index.html | Tipping the Velvet | Books to Scrape - Sandbox
2 pages | 2.00 credits | 18 s | navigation pages (free): 1 | skipped: 0
understood as: Individual product detail pages for books.

The crawl understood the instruction as individual book pages, read one navigation page to get there, and returned two books for 2 credits. Where Map returned the site's structure, Crawl returned the pages at the end of it. A few settings keep a crawl on target:

  • crawl_instruction should name the kind of page you want. "Individual book pages" returns books, and "All pages" returns category and listing pages too.
  • A crawl stays under the start URL's path. Start at the section you want, or set crawl_entire_domain=True and fence it with include_paths.
  • respect_robots is off by default on both Map and Crawl. Set respect_robots=True if your use requires it.
  • The crawl report lists every link it skipped with a reason, such as not_relevant or outside_start_path, so a missing page is a question you can answer.

Three sites, three structures

Put the evidence side by side:

  • books.toscrape.com has no sitemap. Asking Map for the sitemap alone finds nothing. Map listed 124 URLs from page links in 1.8 seconds for 1 credit, and they are the site's structure. Crawl returned the book pages themselves, 2 credits for 2 pages in 18 seconds.
  • yarnpkg.com has a complete sitemap. One file gave 407 URLs in 0.7 seconds, and the audit found nothing the sitemap leaves out. Reading the sitemap wins.
  • github.com has a partial sitemap. The marketing sitemap lists 376 URLs, 122 links in the sample fall outside it, and one listed page doesn't load.
[NEED: for yarnpkg.com and github.com, the URLs found by client.map(site) and by a bounded crawl, their overlap with the sitemap, what only one method found, time and credits]

The decision tree

Work down the questions in order:

  • Do you already have the URLs? Batch scrape them. You don't need any of the three.
  • Do you only need the URLs, not the page content? Read the sitemap if the site has one you trust, which is free (check it with the audit above), or ask Map for sitemap="only" for 1 credit. If the sitemap is missing, partial or stale, use Map with its defaults, and add search to narrow the list to a topic.
  • Do you need page content, and can you list the pages first? Map the site, filter the URLs, then batch scrape them. That is predictable and repeatable, and Map a website and scrape only the pages you need shows the flow.
  • Do you need content from pages you can describe but can't list? Crawl with an instruction, start in the right section, and fence it with include_paths. The Crawl API guide covers crawl settings in depth.

Mistakes to avoid

  • Crawling to get a list of URLs. Crawl charges per page returned and reads content you may not need. Map lists URLs for 1 credit.
  • Trusting a sitemap as complete. The github.com sitemap above is a section of a site. Audit it before you rely on it.
  • Mapping when you need content. Map returns URLs and link text. It doesn't read the pages.
  • Describing the pages loosely. An instruction such as "All pages" returns category and listing pages along with the pages you wanted.

What this comparison doesn't cover

  • Map and Crawl depend on how a site links its pages, so run Map on your own site before you plan a crawl.
  • The audit samples 20 pages. It shows whether a sitemap covers the links near its own pages, not whether it covers the whole site.
  • Results change as sites change, and a sitemap that is complete today can be stale next month.
  • Check a site's terms and robots rules before you crawl it.

Conclusion

The cheapest tool that answers your question is the right one. A sitemap you trust is free, Map covers a site with no usable sitemap for 1 credit, and Crawl is for the pages themselves. Spidra gives you all three behind one account, so you pick by the job and not by what is available:

  • Map costs 1 credit whatever the number of URLs. A site with no sitemap costs the same to map as a site with a huge one, and a map that finds nothing is free.
  • Crawl returns only the pages you describe. Pages it reads to find them are free, and a report explains every link it skipped.
  • Failures are free. Failed pages and failed crawls aren't charged.
  • Fetching is handled. Real browsers, proxies and CAPTCHA solving are included, so you spend your time on the question and not on getting the page.
  • The next step is in the same account. Batch scrape the URLs you pick with a schema, search for sites when you don't have one, or parse documents you find, all on one credit balance.

Every plan has every feature, and the dashboard's Code button writes the request for whatever you set up. Create a free account, set SPIDRA_API_KEY, and map a site you care about before you decide whether it needs a crawl.

Frequently asked questions

A sitemap is a file a site publishes that lists the URLs it chooses to expose. Crawling follows links from a start page to find pages and returns their content. A sitemap is free and fast but only as complete as the site makes it, while a crawl finds linked pages and reads them.

Share this article

You build the product.
Spidra handles the data work.

Start with 300 free credits, about 300 pages. No credit card required.