Sub topic 2
Fetching a page: requests, status codes, and redirects
Fetching is the first stage where a crawler touches your server. This chapter covers what a crawler sends, how it reads the response, and what it does with each status code. It assumes you know what an HTTP request and response look like, can read short Python snippets, and have seen a status code such as 404 before. The previous chapter gave the overall pipeline. This one zooms in on the fetch step. robots.txt is covered in the next chapter, so the fetcher here skips the permission check.
What a crawler sends
A crawler is an HTTP client with a job. For each URL it sends a GET request and reads the response. A few request headers matter for crawling:
User-Agentnames the crawler. Site owners use it to write robots.txt rules and to recognize bot traffic in logs.AcceptandAccept-Encodingtell the server which formats the crawler can handle, such as HTML or gzip.If-None-MatchandIf-Modified-Sincemake the request conditional. They let the server answer "unchanged" without resending the page. The recrawl chapter returns to this.
A crawler may also send HEAD requests, which return headers without a body. They are cheap, but many servers handle them badly, so most crawlers use GET for pages they care about.
What the response tells the crawler
The response has three parts the crawler cares about: the status code, the headers, and the body. The status code decides what happens next. The headers add detail, for example Content-Type (is this HTML, a PDF, an image?), Location (where a redirect points), and Retry-After (how long to wait). The body is only read when the status and content type make it worth reading.
| Status | Meaning | Typical crawler behavior |
|---|---|---|
| 200 | OK | Read the body and pass it on for parsing. |
| 301, 308 | Permanent redirect | Follow it. Treat the target as the preferred URL. |
| 302, 303, 307 | Temporary redirect | Follow it. Usually keep the original URL as preferred. |
| 304 | Not modified | Reuse the stored copy. No body is sent. |
| 404 | Not found | Mark the URL as missing. Retry later at a lower rate. |
| 410 | Gone | Treat as permanently removed. Drop it sooner than a 404. |
| 429 | Too many requests | Slow down. Honor `Retry-After` if present. |
| 500, 502, 503 | Server error or unavailable | Retry later. Reduce the crawl rate for the host. |
Search engines document slightly different details for each code, so treat this table as the common pattern, not a specification.
Soft errors
A "soft 404" is a page that says "not found" in its text but returns status 200. The crawler sees a successful fetch and may index an empty or useless page. The fix is on the server: return a real 404 or 410 for missing content.
Redirects
A redirect is a 3xx response with a Location header. The crawler requests the new URL, which may redirect again, forming a chain. Three rules govern how a crawler handles them:
Locationcan be relative, so the crawler resolves it against the URL it just requested.- Chains are capped, often at around five hops. Past the cap the crawler gives up and tries again later.
- Loops (A redirects to B, B redirects to A) must be detected, because they never end.
Permanent and temporary redirects differ in what they signal. A 301 or 308 says "this URL has moved for good," so the engine tends to index the target and replace the old URL. A 302 or 307 says "use the other URL for now," so the old URL usually stays as the preferred one. Over time, engines may treat a long-lived 302 as permanent, but you should not depend on that.
Not every redirect is an HTTP status. A <meta http-equiv="refresh"> tag and JavaScript assignments to window.location also move the browser. Crawlers may handle them, but later and less reliably than a plain 301, so use HTTP redirects for moves you care about.
A fetcher that handles redirects itself
Python's urllib follows redirects automatically, which hides the chain. A crawler wants control, so this version turns automatic redirects off and walks the chain itself. It records each hop, caps the length, and stops on loops.
import urllib.error
import urllib.request
from urllib.parse import urljoin
REDIRECT_CODES = {301, 302, 303, 307, 308}
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None # do not follow; the 3xx surfaces as an HTTPError
opener = urllib.request.build_opener(NoRedirect)
def fetch_once(url, user_agent="ExampleBot/1.0"):
req = urllib.request.Request(
url, headers={"User-Agent": user_agent, "Accept": "text/html"}
)
try:
with opener.open(req, timeout=10) as resp:
return resp.status, resp.headers, resp.read()
except urllib.error.HTTPError as err:
return err.code, err.headers, b""
def fetch(url, max_hops=5):
chain = [url]
for _ in range(max_hops + 1):
status, headers, body = fetch_once(chain[-1])
if status in REDIRECT_CODES:
location = headers.get("Location")
if not location:
return {"outcome": "bad_redirect", "chain": chain}
target = urljoin(chain[-1], location)
if target in chain:
return {"outcome": "loop", "chain": chain + [target]}
chain.append(target)
continue
return {
"outcome": "ok" if status == 200 else "status_" + str(status),
"status": status,
"chain": chain,
"content_type": headers.get("Content-Type"),
"body": body,
}
return {"outcome": "too_many_hops", "chain": chain}
if __name__ == "__main__":
result = fetch("http://example.com/")
print(result["outcome"], result["chain"])Three details are worth noticing. urljoin handles relative Location values. The target in chain check catches loops before they use up the hop cap. The function returns an outcome label instead of raising, because a crawler treats a failed fetch as normal data to record, not as a crash.
The code leaves out several things a real crawler needs: robots.txt checks, rate limits, size limits on the body, and retries.
Edge cases that affect crawling
Timeouts and slow servers
A server that never answers can stall a crawler worker. Always set a timeout, as the code does with timeout=10. A host that times out often gets a lower crawl rate, because the crawler reads slowness as a sign of overload.
Content type and size
The Content-Type header decides whether the body is parsed as HTML, handled as a PDF, or skipped as an image or binary file. Crawlers also cap how many bytes they read from one response. Content past the cap may never be seen, so very large pages can lose their tail.
Character encoding
The body is bytes. The crawler picks an encoding from the Content-Type header, a <meta charset> tag, or by guessing. A wrong guess produces garbled text, which later breaks tokenization. The sample code decodes with replacement in the crawler chapter for the same reason.
HTTP versus HTTPS and host variants
http://example.com/, https://example.com/, and https://www.example.com/ are different URLs. Sites usually redirect all variants to one with a 301. Without that, the engine may crawl several copies, which the canonicalization chapter covers.
Redirects that change behavior
For 301 and 302, some clients historically switch POST to GET. Crawlers only use GET, so this rarely matters here. The distinction between 307/308 (method preserved) and 302/301 matters more to application developers.
Common errors
- Following redirects without a hop limit, which lets loops run forever.
- Treating a 5xx or 429 as "the page does not exist" and dropping the URL, when a retry would succeed.
- Resolving
Locationagainst the wrong base. Always resolve against the URL that produced the redirect. - Ignoring
Content-Typeand trying to parse a PDF or image as HTML. - Sending a generic or missing
User-Agent, so the site cannot identify the crawler or apply bot-specific rules.
Exercise
A crawler requests https://example.com/a and gets a 301 with Location: /b. It requests https://example.com/b and gets a 302 with Location: /a. What should the crawler do, and which line of the sample fetch function handles it?
Show answer
It should stop and record a redirect loop, instead of retrying until the hop cap. After resolving /a against https://example.com/b, the target https://example.com/a is already in chain, so the check if target in chain returns the outcome loop. The hop cap would also end the crawl eventually, but the loop check ends it sooner and gives a clearer diagnosis.
Exercise
A page returns status 200 with the text "Sorry, this page does not exist." Why is that a problem for indexing, and what should the server return instead?
Show answer
The crawler sees a successful fetch, so it parses the body and may index a near-empty page, or many such pages as duplicates. The server should return 404, or 410 if the removal is permanent, so the crawler marks the URL as missing.