When a scraper suddenly returns a 403, 429, 404, timeout, or an empty dataset, the fastest fix is usually better diagnosis rather than more aggressive requests. This guide provides a repeatable troubleshooting process, practical Python examples, an error-code decision path, and a monitoring checklist you can use after each collection run.
Overview
Web scraping failures generally fall into four groups: the server rejected the request, the requested resource changed or disappeared, the response could not be processed, or the scraper extracted the wrong part of the page. The visible symptom can be misleading. For example, a scraper that returns zero records may have received a successful response but used a selector that no longer matches the HTML. A 200 status code therefore does not guarantee a successful scrape.
Start by separating the stages of the job:
- Request: Did the client connect and receive a response?
- Response: What status code, content type, encoding, and body were returned?
- Parsing: Could the HTML, JSON, or other payload be decoded and parsed?
- Extraction: Did the expected elements or fields exist?
- Storage: Were records written, deduplicated, and validated correctly?
This separation prevents a selector problem from being treated as a network problem. It also gives you useful evidence to compare when the same job runs again.
What to track
Record the request and response
Log enough information to reproduce a failure without storing sensitive data unnecessarily. Useful fields include the URL or a redacted URL pattern, timestamp, HTTP method, status code, response content type, response length, elapsed time, retry count, and parser or selector version. Save a small response sample or fixture when permitted, especially for unexpected status codes and challenge pages.
For a basic Python client, make failures visible before attempting to parse the response:
import requests
response = requests.get(
url,
headers={"User-Agent": "ExampleResearchBot/1.0"},
timeout=(5, 30),
)
print({
"status": response.status_code,
"content_type": response.headers.get("Content-Type"),
"bytes": len(response.content),
"elapsed_seconds": response.elapsed.total_seconds(),
})
response.raise_for_status()Use an honest, identifiable user agent where appropriate, follow the site’s published access requirements, and avoid attempting to bypass authentication or access controls. If the site provides a structured API or feed for the data you need, evaluate that option before relying on HTML extraction.
Track extraction health, not only HTTP health
For every run, measure the number of pages requested, successful responses, retries, parse failures, extracted records, duplicate records, and empty pages. Also track a few expected fields, such as the percentage of records containing a title, URL, identifier, or date. These checks catch silent failures that return valid-looking HTML.
A simple validation rule can stop a broken run from replacing good data:
if not records:
raise RuntimeError("No records extracted; inspect the response and selectors")
required_fields = ("title", "url")
missing = [
field for field in required_fields
if sum(bool(item.get(field)) for item in records) == 0
]
if missing:
raise RuntimeError(f"Required fields are empty: {missing}")Keep a small diagnostic fixture
Store representative HTML fixtures for a normal page, an empty result, a changed layout, and any recurring error response that can be retained safely. Test selectors against these fixtures in development or continuous integration. This makes it possible to determine whether a failure came from the target site, a dependency update, or a code change.
Cadence and checkpoints
Use a checkpoint after each run, a review on a monthly or quarterly cadence, and an immediate review when a failure pattern changes. The appropriate interval depends on how often the target changes and how important the collected data is, but the process should remain consistent.
| Symptom | Likely area | First checkpoint |
|---|---|---|
| 403 Forbidden | Access rules, headers, authentication, or request pattern | Inspect the response body and confirm the requested path is allowed |
| 429 Too Many Requests | Request frequency or concurrency | Reduce concurrency and honor the Retry-After header when present |
| 404 Not Found | URL, pagination, slug, or site structure | Open the URL and compare it with the current navigation or API response |
| Timeout or connection error | Network, server latency, or timeout configuration | Separate connect and read timeouts and inspect elapsed time |
| 200 with empty results | Selector, rendering, pagination, or response variant | Save the body and search it for the expected text or element |
| Decode or parse error | Encoding, content type, malformed markup, or unexpected JSON | Inspect raw bytes, headers, and the first part of the response |
Use bounded retries with backoff
Retries are useful for temporary network failures and some server errors, but repeating a rejected request immediately can increase the problem. Use a small maximum attempt count, exponential backoff, and jitter. Do not automatically retry every 4xx response: a missing page, invalid request, or access denial usually needs investigation rather than repetition.
import random
import time
import requests
retryable = {408, 425, 429, 500, 502, 503, 504}
for attempt in range(4):
response = requests.get(url, timeout=(5, 30))
if response.status_code not in retryable:
break
if attempt == 3:
response.raise_for_status()
delay = min(60, 2 ** attempt) + random.uniform(0, 0.5)
time.sleep(delay)When a 429 response includes a usable Retry-After value, treat it as a scheduling signal. Otherwise, slow the job, reduce parallel workers, and add pacing between requests. A reliable scraper should make fewer, observable requests rather than trying to overcome a limit through rapid retries.
How to interpret changes
403: the server rejected the request
A 403 can result from missing authentication, a disallowed path, an invalid request pattern, or a response that differs between automated and interactive clients. First inspect the status, headers, and body. Confirm that the URL is correct and that your request has the necessary, legitimate credentials. Compare a failing response with a known-good response from an approved workflow. Avoid treating a 403 as a prompt to evade access controls; switch to an available API, obtain permission, or revise the collection scope when necessary.
429: the scraper is sending too much or too often
Check request volume by minute, concurrency, pagination behavior, and whether a failed page is being retried in a tight loop. One common bug is starting several workers that each believe they are below the limit. Centralize pacing or use a shared rate limiter. Cache responses where appropriate and resume from the last successful checkpoint instead of restarting the entire collection.
404: the target changed or the URL was generated incorrectly
Check URL construction, trailing slashes, URL encoding, pagination parameters, redirects, and recently changed slugs. A 404 across every page suggests a base URL or routing problem; a 404 on only older records may indicate removed content. Preserve the failing URL and compare it with the site’s current links rather than guessing replacements.
Timeouts, malformed HTML, and encoding failures
Use separate connection and read timeouts so you can distinguish a server that cannot be reached from one that responds slowly. Log elapsed time and response size. For decoding errors, inspect the declared content type and raw response bytes before forcing an encoding. For malformed HTML, use a tolerant parser where appropriate, but add validation because a parser may recover a tree that is structurally different from what your selector expects.
200 responses with no records
Save the response and search for a distinctive phrase that should appear on a successful page. If it is absent, you may have received a login page, an error template, a consent page, or content that requires client-side rendering. If the phrase is present but the selector finds nothing, inspect the DOM and test a narrower, stable selector. Review the selectors guide for patterns that are less dependent on presentation classes.
When content is rendered after the initial request, first check whether the page calls a documented or discoverable data endpoint that you are permitted to use. The guide to HTML scraping versus API access covers that decision. Do not assume that adding a browser is the best fix; it adds operational cost and another layer to debug.
When to revisit
Revisit this guide after every failed collection run, after a dependency or parser upgrade, and whenever a target site changes its navigation, templates, authentication flow, or response format. On a monthly or quarterly schedule, review error rates, average response size, selector coverage, duplicate counts, and the age of your test fixtures. A gradual increase in empty pages can be an early warning even when the job still exits successfully.
Use this practical repair sequence:
- Save the failing URL, timestamp, status, headers, response length, and a safe body sample.
- Classify the failure as request, response, parsing, extraction, or storage.
- Reproduce it with one request and no concurrency.
- Apply the smallest safe change: correct the URL, validate the selector, add a bounded retry, slow the request rate, or update the parser.
- Run the scraper against saved fixtures before returning to live pages.
- Compare record counts and required-field coverage with the last known-good run.
- Record the cause and repair so the next failure can be identified quickly.
For longer-running jobs, combine these checks with incremental collection and resumable checkpoints. The guide to incremental web scraping explains how to avoid duplicates and continue after an interruption. Keeping the troubleshooting log, fixtures, and validation thresholds current turns web scraping errors from mysterious outages into identifiable maintenance tasks.