To crawl only specific paths, you give the crawler a boundary and then check that it stayed inside. A crawl with no boundary follows links wherever they lead: category pages, tag pages, translated copies, the whole site. Every page you didn't want costs credits and adds noise to whatever you feed the results into.
This tutorial builds a crawl that returns only the pages matching your inclusion and exclusion rules. You'll preview which pages the rules would match before you crawl, run narrow and broad crawls from the same start URL, and audit the result against the section you meant to get.
Install the package and put your Spidra key in the environment as SPIDRA_API_KEY:
# pip install spidra
import argparse
import itertools
import json
import os
import re
import sys
import time
from collections import Counter
from dataclasses import asdict, dataclass, field
from urllib.parse import urlsplit
from spidra import (
CrawlParams,
Spidra,
SpidraAuthenticationError,
SpidraError,
SpidraJobFailedError,
SpidraPaymentRequiredError,
SpidraRateLimitError,
SpidraServerError,
SpidraTimeoutError,
SpidraValidationError,
)
A crawl stays where it starts
The Spidra Crawl API keeps a crawl under the start URL's path. A crawl started at https://spidra.io/blog doesn't follow links to /pricing or /about, and it reports them as skipped. Pages it reads only to reach others, such as a category or listing page, are navigation pages, which aren't returned or charged.
That default isn't a filter on what comes back. Here are three crawls of the Spidra blog, all started from the same URL, https://spidra.io/blog:
Crawl | Rules | What came back | What the report showed |
|---|---|---|---|
1 | None, with the instruction "All pages" | The blog index, six category pages and three posts | 20 links skipped as |
2 | The instruction "Individual blog posts" | Ten posts | 55 links skipped: 32 |
3 |
| The blog index and nine posts |
|
"All pages" means all pages, category pages included. Describing the page you want (crawl 2) and excluding a path (crawl 3) both fix it, but the instruction steers the crawl while a path rule is a hard boundary. The path rule is also cheaper, because no AI reads the pages.
The settings that decide what comes back
These parameters set the boundary. In Python they are the fields of CrawlParams:
Setting | What it does |
|---|---|
Start URL | Where the crawl begins. By default it stays under this path. |
| Only pages whose path matches one of these patterns are returned. |
| Pages whose path matches one of these patterns are left out. |
| Follow links anywhere on the same domain. Pair it with path rules. |
| Clicks from the start page. |
| URLs that differ only by query string count as one page. |
The docs describe the patterns as globs or regexes, and add one warning: a pattern matches anywhere in the path. So /books/* also matches /catalogue/category/books/…. That sentence decides whether your crawl is clean.
A pattern matches anywhere in the path
The same pattern means different things in different tools. As of December 2026, Python's fnmatch anchors at the start of the string and lets * cross a slash. JavaScript glob libraries such as minimatch and picomatch make * stop at a slash, so /blog/* misses /blog/2026/post, and ** crosses it. Scrapy applies its link rules as regular expressions searched anywhere in the URL.
So a pattern you've used elsewhere may match more or fewer pages here. Rather than guess, write the matching rules down as settings you can change. Only the first one, unanchored matching, is documented, so the others are questions to test:
@dataclass(frozen=True)
class Semantics:
"""How a glob matches. Only anchor_start=False is documented, so the rest can be checked."""
anchor_start: bool = False # must the pattern match from the first character of the path?
anchor_end: bool = False # must it match through the last character?
star_crosses_slash: bool = True # does * match a "/"?
ignore_case: bool = False
DOCUMENTED = Semantics()
STRICT = Semantics(anchor_start=True, anchor_end=True, star_crosses_slash=False)
def all_semantics():
"""Every combination of the three open questions, each with a readable name."""
out = []
for start, end, cross in itertools.product((False, True), repeat=3):
name = (
f"{'start-anchored' if start else 'anywhere'}, {'end-anchored' if end else 'open end'}"
)
out.append(
(f"{name}, * {'crosses' if cross else 'stops at'} /", Semantics(start, end, cross))
)
return out
def glob_to_regex(pattern, star_crosses):
"""** always crosses a slash. * and ? cross it only if star_crosses is set."""
star, one = (".*", ".") if star_crosses else ("[^/]*", "[^/]")
parts = re.split(r"(\*\*|\*|\?)", pattern)
return "".join(
".*" if p == "**" else star if p == "*" else one if p == "?" else re.escape(p)
for p in parts
)
def compile_rule(pattern, semantics=DOCUMENTED, kind="glob"):
"""A compiled rule. A pattern is a glob unless kind is 'regex'."""
if not pattern.strip():
raise ValueError("a path pattern can't be empty")
body = pattern if kind == "regex" else glob_to_regex(pattern, semantics.star_crosses_slash)
if kind == "glob":
body = (
("^" if semantics.anchor_start else "") + body + ("$" if semantics.anchor_end else "")
)
try:
return re.compile(body, re.I if semantics.ignore_case else 0)
except re.error as error:
raise ValueError(f"not a valid pattern: {pattern!r} ({error})") from error
def path_of(url):
"""The path part of a URL. The query string and fragment are not part of it."""
return urlsplit(url.strip()).path or "/"
class Matcher:
"""Include and exclude rules. Exclude is checked first, which is an assumption to test."""
def __init__(self, include=(), exclude=(), semantics=DOCUMENTED, kind="glob"):
self.include = [compile_rule(p, semantics, kind) for p in include]
self.exclude = [compile_rule(p, semantics, kind) for p in exclude]
self.semantics = semantics
def decide(self, path):
"""An empty string if the path passes, otherwise the reason Spidra's report would give."""
if any(rule.search(path) for rule in self.exclude):
return "exclude_pattern"
if self.include and not any(rule.search(path) for rule in self.include):
return "include_pattern"
return ""
Semantics holds the three open questions: does a pattern have to match from the start of the path, to the end of it, and does * match a slash. Matcher applies include and exclude rules and returns the reason Spidra's report would give for a path it rejects. Exclude is checked first, which is also an assumption worth testing.
paths = ["/catalogue/category/books/mystery_3/", "/blog/books/best-books-of-2026"]
paths += ["/books/", "/blog/2026/post-a"]
for name, semantics in (("anywhere", DOCUMENTED), ("anchored", STRICT)):
matcher = Matcher(["/books/*"], semantics=semantics)
print(f"{name:9s}", [p for p in paths if not matcher.decide(p)])
Output:
anywhere ['/catalogue/category/books/mystery_3/', '/blog/books/best-books-of-2026', '/books/']
anchored ['/books/']
Read as documented, /books/* returns the category page, the blog post that merely mentions books, and /books/. Read as anchored, it returns only /books/. If you meant the catalogue's books section, the blog post is noise, and the crawl would return it.
Preview before you crawl
You can find this out for the price of a Map call. Map lists a site's URLs without scraping them, and your rules can be applied to that list locally. The preview applies the same order a crawl uses: other domains, files, the start path, then your include and exclude rules:
FILE_TYPES = tuple("." + e for e in "png jpg jpeg gif svg webp pdf zip gz mp4 css js ico".split())
def under(path, start_path):
"""By default a crawl stays under the start URL's path. /blog contains /blog/x, not /blogger."""
base = start_path.rstrip("/")
return not base or path.rstrip("/") == base or path.startswith(base + "/")
def classify(url, start_url, matcher, entire_domain=False):
"""Why a URL would be left out, or an empty string if it would be returned."""
if (urlsplit(url).hostname or "").lower() != (urlsplit(start_url).hostname or "").lower():
return "outside_domain"
path = path_of(url)
if path.lower().endswith(FILE_TYPES):
return "file_type"
if not entire_domain and not under(path, path_of(start_url)):
return "outside_start_path"
return matcher.decide(path)
def preview(urls, start_url, matcher, entire_domain=False):
"""Split known URLs into the ones a crawl would return and the ones it would skip."""
keep, skipped = [], []
for url in urls:
reason = classify(url, start_url, matcher, entire_domain)
(skipped if reason else keep).append({"url": url, "reason": reason} if reason else url)
return {
"would_match": keep,
"skipped": skipped,
"by_reason": dict(Counter(s["reason"] for s in skipped)),
}
under keeps a crawl inside the start path, so /blog contains /blog/x and not /blogger. preview splits known URLs into the ones the crawl would return and the ones it would skip, each with a reason. Here is a small made-up shop to try it on:
BASE = "https://shop.example.test"
BOOKS = "/catalogue/category/books/"
SITE = {
"/": ["/catalogue/", "/blog/", "/about"],
"/catalogue/": [BOOKS, "/catalogue/page-2.html", "/about"],
BOOKS: [BOOKS + "mystery_3/", "/catalogue/a-light_1/index.html"],
BOOKS + "mystery_3/": ["/catalogue/the-sleeping-giant_2/index.html"],
"/catalogue/page-2.html": ["/catalogue/a-light_1/index.html"],
"/blog/": ["/blog/2026/post-a", "/blog/books/best-books-of-2026"],
}
paths = sorted(set(SITE) | {link for links in SITE.values() for link in links})
urls = [BASE + p for p in paths]
for include in (["/books/*"], [BOOKS + "*"]):
found = preview(urls, BASE + "/", Matcher(include), entire_domain=True)
print(include, "->", [u.replace(BASE, "") for u in found["would_match"]])
Output:
['/books/*'] -> ['/blog/books/best-books-of-2026', '/catalogue/category/books/', '/catalogue/category/books/mystery_3/']
['/catalogue/category/books/*'] -> ['/catalogue/category/books/', '/catalogue/category/books/mystery_3/']
The first rule would return the blog post. The second names the whole path and would not, so a stricter pattern fixes it before any crawl runs. Neither rule returns the book pages, such as /catalogue/a-light_1/index.html, because their URLs don't contain the section's name. A path rule selects by URL, so a section whose pages live under a different path needs its own rule.
Set the boundary and run the crawl
crawl_params builds the request from your rules and leaves out any option you didn't set. It asks for robots.txt to be respected, because the default is not to. The instruction stays "All pages", so the path rules, not an AI instruction, decide what comes back:
@dataclass
class Run:
name: str
returned: list
report: dict = field(default_factory=dict)
def crawl_params(start, include=(), exclude=(), entire_domain=False, max_depth=None, **extra):
"""The crawl request. Empty options are left out, and robots.txt is always respected."""
rules = {"include_paths": list(include), "exclude_paths": list(exclude), "max_depth": max_depth}
rules = {key: value for key, value in rules.items() if value not in ([], None)}
rules["max_pages"] = extra.get("max_pages", 30)
rules["ignore_query_params"] = extra.get("ignore_query", False)
return CrawlParams(
base_url=start,
crawl_instruction="All pages",
crawl_entire_domain=entire_domain,
respect_robots=True,
**rules,
)
rules = {"include": ["/catalogue/*"], "exclude": ["/catalogue/page-*"]}
params = crawl_params(BASE + "/", entire_domain=True, **rules)
print("include:", params.include_paths, "| exclude:", params.exclude_paths)
print("entire domain:", params.crawl_entire_domain)
print("respect robots.txt:", params.respect_robots)
Output:
include: ['/catalogue/*'] | exclude: ['/catalogue/page-*']
entire domain: True
respect robots.txt: True
These are the exact patterns the crawl will use. /catalogue/* keeps the catalogue, and /catalogue/page-* drops its numbered listing pages. Because crawl_entire_domain is set, the include rule is what keeps the crawl out of the blog.
def wait_for_crawl(client, job_id, poll=3.0, timeout=600.0, sleep=time.sleep):
waited = 0.0
while waited <= timeout:
state = client.get_crawl(job_id)
if state.status == "completed":
return state
if state.status in ("failed", "cancelled"):
raise RuntimeError(
f"the crawl {state.status}: {getattr(state, 'error', '') or ''}".strip()
)
sleep(poll)
waited += poll
raise TimeoutError("the crawl did not finish in time")
def read_report(client, job_id):
"""What the crawl understood, how many pages it only read, and what it skipped and why."""
report = client.crawl_report(job_id, limit=200).report
blocked = {}
for item in report.skipped_urls:
blocked.setdefault(item.reason, []).append(item.url)
skipped = {row.reason: row.count for row in report.skipped}
return {
"understood_as": report.understood_as,
"navigation_pages": report.navigation_pages,
"skipped": skipped,
"blocked": blocked,
}
def run_crawl(client, name, start, poll=3.0, sleep=time.sleep, **options):
"""Start a crawl, wait for it, and return its pages and report as a Run."""
job_id = client.start_crawl(crawl_params(start, **options)).job_id
state = wait_for_crawl(client, job_id, poll, sleep=sleep)
return Run(name, [page.url for page in state.result], read_report(client, job_id))
run_crawl starts the crawl, waits for it, and returns the URLs it returned together with its report. The report says what the crawl understood, how many pages it only read to find others, and the URLs it skipped, grouped by reason, such as include_pattern, exclude_pattern and outside_start_path.
Audit the result against the section
A crawl that returned pages doesn't mean it returned the right ones. The audit checks each returned URL against the section you meant to get, which is a start-anchored prefix and not a pattern with the same ambiguity:
def section_matcher(prefixes):
"""The section you intended: any path that starts with one of these prefixes."""
return Matcher([p.rstrip("*") + "*" for p in prefixes], semantics=Semantics(anchor_start=True))
def audit(returned, section):
"""How many returned URLs are outside the intended section, and which ones."""
bad = [
{"url": u, "reason": section.decide(path_of(u))}
for u in returned
if section.decide(path_of(u))
]
share = round(len(bad) / len(returned), 3) if returned else 0.0
return {
"returned": len(returned),
"inside": len(returned) - len(bad),
"outside": len(bad),
"noise": share,
"violations": bad,
}
audit counts the returned pages that fall outside the section and names each one. Here a small crawler stands in for a real crawl on the made-up shop. It reads through pages that fail an include rule to reach pages that match, which is an assumption to confirm on your own site:
def tiny_crawl(start, matcher, entire_domain=False, max_depth=None):
seen, queue, returned = {start}, [(start, 0)], []
while queue:
path, depth = queue.pop(0)
reason = classify(BASE + path, BASE + start, matcher, entire_domain)
returned += [] if reason else [path]
if reason in ("", "include_pattern") and (max_depth is None or depth < max_depth):
for link in SITE.get(path, []):
if link not in seen:
seen.add(link)
queue.append((link, depth + 1))
return returned
section = section_matcher([BOOKS])
returned = [BASE + p for p in tiny_crawl("/", Matcher(["/books/*"]), True)]
found = audit(returned, section)
print(f"{found['returned']} returned, {found['outside']} outside the section", end=" ")
print(f"({found['noise']:.0%} noise)")
for v in found["violations"]:
print("outside:", v["url"].replace(BASE, ""))
Output:
3 returned, 1 outside the section (33% noise)
outside: /blog/books/best-books-of-2026
The audit finds the blog post that the loose pattern let through. That's the check a quick look at the results would miss, because the page looks plausible: its path contains /books/.
Compare a narrow crawl with a broad one
Run both from the same start URL and the difference is the case for your rules. The table adds the share of returned pages that fall outside the section. Its last two columns come from a real crawl's report, so they stay empty for this stand-in:
HEADER = ["run", "returned", "outside the section", "noise", "navigation pages", "skipped"]
def row_for(run, section):
found = audit(run.returned, section)
skipped = ", ".join(f"{k} {v}" for k, v in run.report.get("skipped", {}).items()) or "none"
nav = run.report.get("navigation_pages", 0)
return [run.name, found["returned"], found["outside"], f"{found['noise']:.0%}", nav, skipped]
def compare_rows(runs, section):
"""One row per crawl: what it returned, how much was outside the section, what it skipped."""
return [row_for(run, section) for run in runs]
def render_table(rows):
lines = ["| " + " | ".join(HEADER) + " |", "|" + "---|" * len(HEADER)]
return "\n".join(lines + ["| " + " | ".join(str(cell) for cell in row) + " |" for row in rows])
runs = []
for name, rules in (("broad", Matcher()), ("narrow", Matcher([BOOKS + "*"]))):
runs.append(Run(name, [BASE + p for p in tiny_crawl("/", rules, True)]))
print(render_table(compare_rows(runs, section)))
Output:
| run | returned | outside the section | noise | navigation pages | skipped |
|---|---|---|---|---|---|
| broad | 11 | 9 | 82% | 0 | none |
| narrow | 2 | 0 | 0% | 0 | none |
The broad crawl returns every reachable page, and most of them are outside the books section. The narrow crawl returns only the section. On a real site the broad run is also the one that costs more and fills your index with pages you'd have to filter out later.
Choose depth carefully
maxDepth counts clicks from the start page, and it's tempting as a way to keep a crawl small. It limits how far the crawl looks, not what it returns, so it can hide the pages you want. Here the first book page sits three clicks from the start, and the second sits four:
items = Matcher(["/index.html"])
for depth in range(5):
print("max depth", depth, "-> returned:", len(tiny_crawl("/", items, True, depth)))
Output:
max depth 0 -> returned: 0
max depth 1 -> returned: 0
max depth 2 -> returned: 0
max depth 3 -> returned: 1
max depth 4 -> returned: 2
At depth 2 the crawl has reached only listing pages, so nothing matches. Depth 3 finds one item and depth 4 finds both. The docs advise leaving maxDepth unset for this reason: target pages often sit behind a category or a second listing page. Use path rules to fence a crawl, and use depth only when you know how deep your pages are.
Learn how the crawl matches your patterns
The documentation settles one rule and leaves the rest open, and your site is the place to test them. Run a crawl with a few patterns that distinguish the readings, then read the report. It lists the URLs each pattern skipped. consistent_semantics checks which readings of the rules would have produced exactly that result:
def agrees(semantics, include, exclude, returned, blocked):
"""Would these matching rules have produced what the crawl actually did? Only skips caused by
a pattern say anything about matching, so other skip reasons are ignored."""
matcher = Matcher(include, exclude, semantics)
passed = all(matcher.decide(path_of(u)) == "" for u in returned)
patterns = {
r: urls for r, urls in blocked.items() if r in ("include_pattern", "exclude_pattern")
}
held = all(
matcher.decide(path_of(u)) == reason for reason, urls in patterns.items() for u in urls
)
return passed and held
def consistent_semantics(include, exclude, returned, blocked):
"""The matching rules that explain a crawl. blocked maps a skip reason to its URLs."""
return [
name for name, sem in all_semantics() if agrees(sem, include, exclude, returned, blocked)
]
base = "https://spidra.io/blog/category/"
names = ["trends", "announcements", "guides", "best-practices", "case-studies", "tutorials"]
blocked = {"exclude_pattern": [base + name for name in names]}
fits = consistent_semantics([], ["/blog/category/*"], ["https://spidra.io/blog"], blocked)
print(len(fits), "of", len(all_semantics()), "readings fit this crawl")
Output:
8 of 8 readings fit this crawl
That's the real exclusion run from the Spidra blog, and it fits all eight readings. A simple exclusion like /blog/category/* can't tell you how anchoring works, because every reading excludes the same six pages. A pattern like /books/*, which could match in more than one place, can. Here is what the same check says when the crawler matches from the start of the path:
truth = Matcher(["/books/*"], semantics=Semantics(anchor_start=True))
returned = tiny_crawl("/", truth, True)
paths = sorted(set(SITE) | {link for links in SITE.values() for link in links})
blocked = {"include_pattern": [p for p in paths if truth.decide(p) == "include_pattern"]}
fits = consistent_semantics(["/books/*"], [], returned, blocked)
print(len(fits), "of", len(all_semantics()), "readings fit:", fits)
Output:
4 of 8 readings fit: ['start-anchored, open end, * stops at /', 'start-anchored, open end, * crosses /', 'start-anchored, end-anchored, * stops at /', 'start-anchored, end-anchored, * crosses /']
When the crawl matches from the start, a pattern that could match anywhere narrows the readings to the four that match from the start, and the audit says so. A pattern with a * in the middle would separate those four. Run the same check on your site's crawl before you rely on a pattern.
The finished command
The command wraps all of it: a preview, the crawl, the audit and an optional broad run for comparison. It saves every crawl to a file and exits with a code a scheduler can read:
NO_API_KEY = 3 # missing or rejected
RULES = [
(
SpidraAuthenticationError,
NO_API_KEY,
"the Spidra API key was rejected. Check SPIDRA_API_KEY.",
),
(SpidraPaymentRequiredError, 4, "the account is out of credits, or its payment is overdue."),
(SpidraRateLimitError, 5, "too many requests. Wait a moment and try again."),
(SpidraTimeoutError, 6, "Spidra took too long to answer."),
(SpidraJobFailedError, 7, None), # its own message says what failed
(SpidraValidationError, 8, None), # its own message says which option was refused
(SpidraServerError, 9, "Spidra had a problem on its side. Try again."),
]
UNKNOWN = 1
NO_PAGES = 10 # the crawl returned nothing
BAD_OPTIONS = 11 # a pattern or option can't be used
AUDIT_FAILED = 13 # the crawl returned pages outside the section
class Failure(Exception):
def __init__(self, message, code):
super().__init__(message)
self.message, self.code = message, code
def explain(error):
"""The first rule that matches wins. List the specific errors before the general one."""
for kind, code, text in RULES:
if isinstance(error, kind):
return Failure(text or str(error), code)
return Failure(str(error), UNKNOWN)
def failure_from(error):
return explain(error) if isinstance(error, SpidraError) else Failure(str(error), UNKNOWN)
def split_list(text):
"""'a, b,,c' becomes ['a', 'b', 'c']."""
return [part.strip() for part in (text or "").split(",") if part.strip()]
def add_rules(ask):
ask.add_argument("start", help="the URL to start crawling from")
ask.add_argument("--include", help="comma-separated path patterns to keep")
ask.add_argument("--exclude", help="comma-separated path patterns to leave out")
ask.add_argument("--section", help="path prefixes you intend to get (default: the start path)")
ask.add_argument(
"--entire-domain", action="store_true", help="follow links anywhere on the domain"
)
ask.add_argument(
"--max-depth", type=int, help="clicks from the start page (usually leave unset)"
)
def build_parser():
ask = argparse.ArgumentParser(
description="Crawl only the URL paths you choose, and audit the result."
)
add_rules(ask)
add_run_options(ask)
return ask
def make_client():
if not os.environ.get("SPIDRA_API_KEY"):
raise Failure("set SPIDRA_API_KEY to your Spidra key first.", NO_API_KEY)
return Spidra(api_key=os.environ["SPIDRA_API_KEY"], api_url=os.environ.get("SPIDRA_API_URL"))
def options_from(args):
return {
"include": split_list(args.include),
"exclude": split_list(args.exclude),
"entire_domain": args.entire_domain,
"max_depth": args.max_depth,
"max_pages": args.max_pages,
"ignore_query": args.ignore_query_params,
}
def check_rules(args):
try:
Matcher(split_list(args.include), split_list(args.exclude))
except ValueError as error:
raise Failure(str(error), BAD_OPTIONS) from error
if args.max_depth is not None and args.max_depth < 0:
raise Failure("--max-depth can't be negative.", BAD_OPTIONS)
def preview_lines(client, args):
semantics = STRICT if args.semantics == "strict" else DOCUMENTED
matcher = Matcher(split_list(args.include), split_list(args.exclude), semantics)
urls = [link.url for link in client.map(args.start, limit=500, respect_robots=True).links]
found = preview(urls, args.start, matcher, args.entire_domain)
kept = found["would_match"]
lines = [f"Would return {len(kept)} of {len(urls)} mapped URLs ({args.semantics} matching)"]
lines += [f" skip {reason}: {count}" for reason, count in found["by_reason"].items()]
return lines + [f" match {url}" for url in kept[:15]]
def run_all(client, args, sleep):
options = options_from(args)
runs = [run_crawl(client, "narrow", args.start, sleep=sleep, **options)]
if args.compare_broad:
broad = {**options, "include": [], "exclude": [], "entire_domain": True}
runs.insert(0, run_crawl(client, "broad", args.start, sleep=sleep, **broad))
return runs
def result_lines(runs, section):
narrow = next(r for r in runs if r.name == "narrow")
found = audit(narrow.returned, section)
head = f"Returned {found['returned']} pages: {found['inside']} inside the section"
lines = [f"{head}, {found['outside']} outside ({found['noise']:.0%} noise)"]
lines += [f" outside: {v['url']}" for v in found["violations"][:10]]
return lines + (["", render_table(compare_rows(runs, section))] if len(runs) > 1 else [])
def crawl_lines(client, args, sleep):
section = section_matcher(split_list(args.section) or [path_of(args.start)])
runs = run_all(client, args, sleep)
with open(args.out, "w", encoding="utf-8") as handle:
json.dump([asdict(run) for run in runs], handle, indent=2)
narrow = next(r for r in runs if r.name == "narrow")
leaked = audit(narrow.returned, section)["outside"]
return result_lines(runs, section), (
NO_PAGES if not narrow.returned else AUDIT_FAILED if leaked else 0
)
def main(argv=None, client=None, sleep=time.sleep):
args = build_parser().parse_args(argv)
try:
check_rules(args)
lines, code = run_command(client or make_client(), args, sleep)
print("\n".join(lines))
return code
except Exception as error: # a Failure, a Spidra error, a timeout or a failed crawl: one line
failure = error if isinstance(error, Failure) else failure_from(error)
print(f"error: {failure.message}", file=sys.stderr)
return failure.code
Save the pieces as crawl_section.py. First preview what your rules would match:
python crawl_section.py https://example.com/ --entire-domain --include "/catalogue/category/books/*" --preview
Then crawl, and compare against a broad run from the same start URL:
python crawl_section.py https://example.com/ --entire-domain --include "/catalogue/category/books/*" --section /catalogue/category/books/ --compare-broad
The exit code says what happened: 0 for success, 3 for the key, 4 for credits or an overdue payment, 5 for the rate limit, 10 when the crawl returned nothing, 11 for options that can't be used, and 13 when the crawl returned pages outside your section. That last one is the code to alert on.
What this doesn't do
It models matching rules; it doesn't know Spidra's. The documentation says patterns are globs or regexes and match anywhere in the path, and it doesn't say how the two are told apart, whether * crosses a slash, or whether case matters, so check them with the last section's method on your own site. The audit checks URLs, not content, so a page at the right path can still be the wrong kind of page. And a start-path boundary doesn't replace the site's rules: respect its robots.txt and terms.
Spend credits on the section, not the site
You now have a crawl with an explicit boundary, a preview that shows what it will return before it runs, and an audit that proves it stayed inside. The pages outside your section are the ones that cost you twice, once to crawl and again to filter out.
Here is what Spidra gives you for that job:
- A boundary you control.
includePathsandexcludePathsare a hard fence, while the instruction only steers. The default start-path scope keeps a crawl in the section it began in. - A report that explains every skipped page. Each skipped URL has a reason, such as
outside_start_path,include_pattern,exclude_patternorfile_type, and the page it was found on. - Navigation pages that aren't charged. The crawl can read a category page to reach the pages behind it without billing you for the category.
- Depth and domain controls.
maxDepth,crawlEntireDomain,ignoreQueryParamsandallowSubdomainsshape the crawl without changing your code. - Respect for the site. With
respectRobotsset, the crawl honors robots.txt, so a recurring crawl stays polite. - Cheaper than reading with AI. A path rule fences a crawl without an AI reading each page.
Narrow crawls are how a practical ingestion job stays small and clean. Spidra can't know which pages you meant, and this tutorial doesn't pretend it can. What it gives you is a boundary, a report, and the evidence to check them against each other.
Create a free account, preview your rules on a site your product depends on, and run the audit on the crawl. The Crawl docs list every option, and our Crawl API guide covers extraction from the pages you keep.