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:
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_childrencaps 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
