Design a web crawler in Python by separating five concerns: a frontier that tracks which URLs to visit, a fetcher that retrieves pages politely, a parser that extracts links and data, a deduplication layer that prevents repeat work, and a storage step that persists results. The key condition is legal and ethical: check a site's terms and robots.txt rules before crawling, identify your bot in the request headers, and limit request rate. A crawler that ignores those constraints is a liability no matter how clean the code is.
This guide walks through the design decisions in the order you'd actually make them, from scope definition to a runnable structure you can extend. Python's standard library covers nearly all of the core, and third-party libraries help where they earn their place. Along the way you'll see the trade-offs that separate a weekend script from something that can run for days without hammering a server or filling a disk with duplicate HTML.
Define Scope, Purpose, and Compliance Rules First
Every crawler starts as a question: what are you trying to collect, from where, and how often? A price-monitoring bot for twenty product pages is a different machine from a research crawler that follows links across thousands of domains. Nail down three things before writing code.
First, the target set. Are you crawling one site, a list of seed URLs, or the open web? Restricting to specific domains with an allowlist is the single biggest simplification you can make, because it constrains the frontier and makes rate limiting tractable.
Second, the data you need. If you only need page titles and meta descriptions, you can skip rendering JavaScript entirely. If the content is generated client-side, you'll need a headless browser, which multiplies resource cost. Decide early; retrofitting a browser-based fetcher into a lightweight design is painful.
Third, the rules. Check the site's terms of service for crawling restrictions, read robots.txt (Python's urllib.robotparser parses it for you), and set a realistic delay between requests. Respect Crawl-delay if present. If a site offers an API or bulk data export, use it instead of crawling; that's almost always the better engineering choice. Identify your crawler with a descriptive User-Agent string that includes a contact URL, so site operators can reach you if something goes wrong.
A useful scope document is a short list: seed URLs, allowed domains, disallowed paths, fields to extract, crawl frequency, and a hard page cap. That cap matters more than beginners expect—it's your circuit breaker against runaway link-following.
Understand the Architecture Before You Code
A web crawler is a loop, but a well-designed one is a pipeline. The classic components:
Frontier (URL queue): an ordered store of URLs waiting to be fetched. A queue gives breadth-first order; a priority queue lets you rank by depth, estimated value, or freshness. Fetcher: makes HTTP requests, handles redirects, retries, and timeouts, and returns raw content plus metadata. Parser: extracts links and target data from HTML or other formats. Deduplicator: tracks seen URLs and, ideally, seen content, so you don't re-process the same page reached via different links. Storage: writes extracted records to a database or files, and logs crawl state so you can resume.
The frontier and deduplicator are where most design mistakes hide. A naive list called seen grows unbounded in memory on large crawls; a set of URLs in a database or a Bloom filter scales better. If you crawl the same site daily, you also need a freshness policy: don't refetch pages you fetched an hour ago unless they're expected to change.
There's a tension between breadth and depth. Breadth-first crawling (a FIFO queue) tends to visit high-value hub pages early and spreads load across a site evenly. Depth-first can dive into a single topic subtree but risks trapping you in an infinite calendar or pagination loop. For most general purposes, breadth-first or a priority queue that boosts shallow pages is the safer default.
Set Up Your Python Environment and Dependencies
For a solid, low-dependency build, you need:
Python 3.10 or newer (anything current as of late 2026 works; avoid pinning to an end-of-life release). requests for HTTP, or httpx if you want async support. beautifulsoup4 with lxml for parsing, or selectolax if parsing speed becomes a bottleneck. urllib.parse and urllib.robotparser from the standard library for URL normalization and robots checking. sqlite3 from the standard library for a lightweight persistent frontier and results store. asyncio if you plan concurrent fetching.
Create a virtual environment, install these, and confirm the versions. If you're parsing JavaScript-heavy sites, add playwright and be aware of the resource cost. Avoid launching a browser for every page; share one browser context across requests and reuse it.
One dependency trap: don't reach for a crawler framework on day one. Frameworks like Scrapy are excellent and battle-tested, but the point of designing a crawler is to understand the pipeline. Build small first, then adopt a framework when your scale demands it—Scrapy's scheduler, item pipelines, and throttling are genuinely hard to reimplement well.
Build the Frontier and Deduplication Layer
The frontier should hold entries richer than bare strings: the URL, its depth, the referring URL (useful for debugging), and a timestamp. A SQLite table works well for a first build because it survives crashes and supports resumption.
Normalization matters because , , and are effectively the same target. Lowercasing the host, stripping the www. prefix, and dropping fragments prevents trivially duplicated work. Be careful with query parameter sorting: some sites treat parameter order as significant, so test against your targets before assuming it's safe.
For very large crawls (millions of URLs), a Bloom filter backed by a database for false positives is the standard trade-off: tiny memory footprint, a small chance of skipping a page you haven't actually seen. For thousands of pages, don't bother; a PRIMARY KEY in SQLite is fine and exact.
Fetch Pages Politely and Robustly
The fetcher is where politeness lives. Five behaviors matter:
1: Rotate rate, not IP. A fixed delay between requests per host (often 0.5–2 seconds) is courteous and keeps you out of trouble. Don't spoof user agents or rotate proxies to evade limits; that's both unethical and, in many jurisdictions, legally risky. 2: Honor Retry-After. On HTTP 429 (Too Many Requests) or 503, wait as instructed before retrying. 3: Set timeouts. Without them, a single hung connection stalls your crawl. A 10-second connect and 30-second read timeout is a reasonable start. 4: Cap retries. Retry transient errors (timeouts, 5xx) a small number of times with exponential backoff; don't retry 4xx except 429. 5: Handle redirects deliberately. Follow a limited number of hops, and record the final URL to dedupe effectively.
The key return is the Response object or None. A None should be logged, not silently dropped—failed pages are data about the crawl, and debugging without failure logs is guesswork. Track a small metrics dict (fetched, skipped, failed, by host) and print it at the end. A success check: after a twenty-page test crawl, the fetched count should match queued pages minus disallowed and duplicate URLs, and failures should have a logged reason.
Parse HTML Without Breaking on Real Sites
Parsing is usually the easiest part, provided you treat markup as untrusted and inconsistent. Use a parser that tolerates malformed HTML (lxml through BeautifulSoup handles this well). Extract links and target fields in one pass if you can.
urljoin is doing hidden work: it resolves relative links like /about and ../pricing against the page URL. Without it, you'll queue garbage. Common traps include javascript:void(0) links, mailto: and tel: URIs, and links with tracking parameters that multiply near-duplicate URLs. Filter by scheme (keep http and https only), then normalize.
If your target content lives inside a specific container, use CSS selectors to confine extraction, and add a fallback for pages where the selector matches nothing, so a single layout change doesn't silently produce empty records. For JSON endpoints or RSS feeds, skip HTML parsing entirely—use json.loads or an XML parser and save yourself the trouble.
Store Results and Maintain Crawl State
Storage has two jobs: keep the extracted data, and keep enough crawl state that you can resume after a crash. SQLite does both for a first build; PostgreSQL makes sense once concurrent workers need to coordinate.
Also store a content hash (e.g., SHA-256 of the normalized body) so you can detect when two different URLs return identical content. This catches pagination loops, print views, and session-token variants that URL normalization misses. For large bodies, store a hash and a local file path rather than the raw HTML in the database.
For resumption, mark frontier rows as pending, fetched, or failed, and on startup requeue anything stuck in pending past a timeout. A crawl that must restart from scratch after a power blip is a crawl you'll only run once.
Scale Concurrency Without Getting Blocked
Concurrency is the lever that turns a toy into a pipeline, but it's also the fastest way to get banned. The rule: concurrency should be per host, not global. Fetching one page from each of ten hosts concurrently is polite; fetching ten pages from one host at once is a hammer.
With asyncio and httpx, you can run a bounded number of in-flight requests and gate them by a per-host semaphore and a delay. Simpler for beginners: a small thread pool (for example, five workers) that all pull from the frontier and apply a per-host timestamp check before fetching.
Watch for the classic async failure: queueing thousands of coroutines at once can exhaust memory before the semaphore helps, because the list of tasks is itself the resource. Pull from the frontier in batches, or use a bounded async queue, and your memory profile stays flat.
Measure before scaling. Time a single-threaded crawl of a hundred pages, then a concurrent one; if the concurrent version only slightly improves throughput because the delay dominates, you're throttled by politeness, not by your code—and that's fine. Throughput isn't the goal; reliable, respectful collection is.
Handle Edge Cases, Failures, and Traps
Real crawls fail in repetitive, predictable ways. Build defenses for these:
Infinite pagination and calendar traps: a ?page=N link that always has a "next" link generates unbounded URLs. Cap depth, cap pages per host, or require pages to add new content before following further. Duplicates via parameters: session IDs, utm_* tags, and sort-order parameters create near-identical URLs. Normalize aggressively, and consider ignoring a configurable allowlist of tracking parameters. Content-type surprises: a URL ending in .html can return a PDF or JSON. Check the Content-Type header and dispatch to the right parser, or skip unsupported types. Encoded and relative links: handle percent-encoding consistently and resolve every link with urljoin. Robots changes mid-crawl: re-check robots.txt periodically or at least per-domain start; a site may tighten rules while you run. Soft 404s: pages returning HTTP 200 with "not found" text. Content hashing and selector checks help; add an explicit stop condition when error rates for a host exceed a threshold.
An explicit stop condition worth wiring in: if a single host returns more than a few consecutive 5xx errors or connection timeouts, back off and pause that host rather than retrying forever. If a site asks you to stop, or robots disallows the path, drop it. And if legal terms are unclear for commercial use, consult a lawyer—that's not a judgment a blog post can make for you.
Choose Between Build, Framework, and Managed Options
The trade-off is scope versus control. Hand-rolled (as above) gives full control and is ideal for learning and for narrowly scoped jobs. Scrapy adds scheduling, throttling, retries, pipelines, and feed exports out of the box; its learning curve is real, but it saves weeks at moderate scale. For JavaScript-rendered sites, Playwright or Selenium handles navigation that requests cannot. Fully managed crawling services handle scale and anti-bot negotiation for a fee but cost visibility and control, and they can be expensive at volume.
| Approach | Best for | Main drawback |
|---|---|---|
| Hand-rolled (requests + SQLite) | Learning, narrow sites, small volumes | You rebuild retries, throttling, resumption |
| Scrapy | Medium-to-large structured crawls | Framework concepts to learn; overkill for ten pages |
| Playwright/Selenium | JS-rendered pages | Heavy CPU/memory; slower per page |
| Managed service | Scale without ops | Cost, less control, vendor policies |
Match the tool to the job rather than the reverse. A 50-page price checker doesn't need a distributed system; a 5-million-page research crawl shouldn't be a single script with a while loop.
Frequently Asked Questions
Is asynchronous Python always faster for crawling? No. Async helps when you're waiting on many network responses at once, but politeness delays and per-host limits often dominate. If you crawl one host slowly, threads or even a simple loop are easier to reason about. Measure the bottleneck before rewriting.
How do I avoid crawling the same page twice? Two layers: normalize and dedupe URLs (strip fragments, lowercase hosts, sort query parameters, follow redirects to a canonical URL), and hash page content to catch different URLs with identical bytes. The first saves requests; the second saves processing.
Can a crawler respect robots.txt and still get blocked? Yes. Servers may rate-limit or block based on IP, behavior, or unclear rules. Back off, slow down, identify honestly, and treat repeated 403s as a signal to stop rather than to escalate. If you need data at that volume, a licensed API or explicit permission is the right route.
How many pages can a single Python process handle? For a hobby crawl, tens of thousands over days is realistic on a modest machine, bottlenecked by storage and politeness delays more than CPU. Beyond that, plan for a persistent database, resumable state, and monitoring—and expect to spend most of your engineering time on reliability rather than fetching.