Python

Building a Reliable Web Scraper in Python with Retries, Proxies, and Rate Limiting

Web scraping is a common technique for collecting publicly accessible information from websites. Developers use it for price monitoring, product research,…

D
DevByteTechnical Author
Published
18 min read1 views
Building a Reliable Web Scraper in Python with Retries, Proxies, and Rate Limiting

Web scraping is a common technique for collecting publicly accessible information from websites. Developers use it for price monitoring, product research, market analysis, content aggregation, and competitive intelligence.

At first, scraping might seem straightforward. Send an HTTP request, parse the HTML, and extract the information you need.

But real-world websites introduce several challenges. Requests can fail because of network timeouts, servers can temporarily return errors, and sending too many requests can overload a website or result in access restrictions. Some websites also require you to configure an authorized proxy when accessing them through a corporate network.

A reliable scraper needs more than a basic HTTP request. It needs controlled retries, sensible timeouts, rate limiting, clear error handling, and a strategy for storing the collected data.

In this tutorial, we'll build a practical web scraper in Python using httpx and BeautifulSoup. We'll implement retry logic, request throttling, optional proxy configuration, HTML parsing, and structured output.

We'll also discuss how to handle common scraping failures and prepare the scraper for production workloads.

1. What Makes a Web Scraper Reliable?

Consider a scraper that collects product names and prices from a website.

A basic implementation might look like this:

import requests
from bs4 import BeautifulSoup

url = "https://example.com/products"

response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

print(soup.title.text)

This works only if the request succeeds, the response contains the expected HTML, and the page structure matches your assumptions.

In production, several things can go wrong:

  • The server takes too long to respond.

  • A temporary network problem interrupts the request.

  • The server returns HTTP 429 because too many requests were sent.

  • The server returns HTTP 500 during a temporary outage.

  • The HTML structure changes.

  • The requested resource no longer exists.

  • The website explicitly disallows automated access to the requested page.

A reliable scraper should handle these situations deliberately.

The main components are:

Timeouts: Prevent requests from waiting indefinitely.

Retries: Retry appropriate temporary failures without repeatedly sending requests that will never succeed.

Rate limiting: Control how frequently requests are sent.

Proxy configuration: Route requests through an authorized intermediary when required by your network or infrastructure.

HTML parsing: Extract data while validating that the expected fields exist.

Error handling: Record failures so that they can be investigated without crashing the entire scraping job.

Logging: Make it possible to understand what happened during a scraping run.

The goal is not to force every request to succeed. It is to make the scraper predictable, respectful, and resilient when failures occur.

2. Choosing the Right Python Libraries

We'll use three main libraries.

HTTPX

HTTPX is an HTTP client that supports both synchronous and asynchronous requests.

Its asynchronous interface is useful when a scraper needs to fetch multiple pages efficiently without creating a separate thread for every request.

Beautiful Soup

Beautiful Soup makes it easier to extract information from HTML documents using CSS selectors and other parsing methods.

Python standard library

We'll also use built-in modules such as:

  • asyncio for asynchronous execution.

  • logging for application logs.

  • os for reading environment variables.

  • random for adding jitter to retry delays.

  • datetime for timestamping collected records.

Create a project directory:

mkdir reliable-python-scraper
cd reliable-python-scraper

Create and activate a virtual environment:

python -m venv venv

On macOS or Linux:

source venv/bin/activate

On Windows:

venv\Scripts\activate

Install the dependencies:

pip install httpx beautifulsoup4

Create a file named scraper.py.

Our project will initially use a single Python file to keep the example easy to follow. As the scraper grows, you can separate HTTP handling, parsing, storage, and scheduling into different modules.

3. Understanding HTTP Status Codes Before Retrying

Before implementing retries, it's important to understand which HTTP failures might be temporary.

Status code

Meaning

Recommended action

200

Successful response

Parse the content

301 or 302

Redirect

Follow redirects when appropriate

403

Forbidden

Stop and investigate access permissions

404

Resource not found

Usually do not retry

408

Request timeout

Retry cautiously

429

Too many requests

Respect Retry-After and reduce request frequency

500

Internal server error

Retry with a bounded delay

502

Bad gateway

Retry cautiously

503

Service unavailable

Respect Retry-After when provided

504

Gateway timeout

Retry cautiously

Not every failure should trigger another request.

For example, retrying a 404 response usually wastes resources because the resource does not exist at that URL.

Similarly, a 403 response should not be treated as a challenge to bypass. It may indicate that automated access is prohibited or that your account lacks permission.

A good retry policy distinguishes between temporary failures and conditions that require human intervention.

4. Creating a Configurable Scraper

Let's start by defining the configuration.

At the top of scraper.py, add:

import asyncio
import json
import logging
import os
import random

from datetime import datetime, timezone
from urllib.parse import urlparse

import httpx

from bs4 import BeautifulSoup


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)

logger = logging.getLogger(__name__)

REQUEST_TIMEOUT = 15.0
MAX_RETRIES = 3
MIN_REQUEST_INTERVAL = 2.0

PROXY_URL = os.getenv("SCRAPER_PROXY_URL")

Let's examine these settings.

REQUEST_TIMEOUT defines the maximum time allowed for an HTTP request according to HTTPX's timeout configuration.

MAX_RETRIES limits the number of retries after the initial attempt.

MIN_REQUEST_INTERVAL defines the minimum interval between request starts to the same host in our implementation.

PROXY_URL is optional. It allows us to configure an authorized proxy through an environment variable rather than hardcoding proxy credentials in the source code.

We'll implement the request handling and rate limiting next.

5. Implementing Rate Limiting

Rate limiting controls how frequently a scraper sends requests.

Without it, a script that loops through hundreds of URLs may send requests much faster than intended.

For example:

for url in urls:
    response = await client.get(url)

Although this example is sequential, it can still generate requests rapidly, especially when the server responds quickly.

When requests are launched concurrently, the problem can become more significant.

A simple solution is to introduce a delay between request starts.

However, a global delay is not always ideal. If your scraper collects information from multiple websites, each host should have its own rate limit.

Let's create a per-host rate limiter:

class HostRateLimiter:
    def __init__(self, min_interval: float = 2.0):
        self.min_interval = min_interval
        self._locks = {}
        self._last_request = {}

    async def wait(self, host: str):
        if host not in self._locks:
            self._locks[host] = asyncio.Lock()

        async with self._locks[host]:
            now = asyncio.get_running_loop().time()

            last_request = self._last_request.get(
                host,
                0.0,
            )

            elapsed = now - last_request
            delay = self.min_interval - elapsed

            if delay > 0:
                await asyncio.sleep(delay)

            self._last_request[host] = (
                asyncio.get_running_loop().time()
            )


rate_limiter = HostRateLimiter(
    min_interval=MIN_REQUEST_INTERVAL
)

How does it work?

The rate limiter maintains two dictionaries:

  • _locks stores an asynchronous lock for each host.

  • _last_request stores the time when the most recent request started.

Before sending a request, the scraper waits until the configured interval has passed.

For example, with a two-second interval, requests to the same host should start at least two seconds apart.

Using a lock ensures that concurrent tasks sharing the same limiter don't all calculate their delays independently and then start together.

This implementation is suitable for a small, single-process scraper. For large-scale systems running multiple workers or machines, you would need a distributed rate limiter or another coordination mechanism.

Important: A local rate limiter only controls the requests made through that limiter. It does not coordinate with other applications using the same network or IP address.

You should also follow any stricter limits documented by the website.

6. Adding Retry Logic with Exponential Backoff

A network request can fail temporarily for reasons outside your control.

Retrying may help, but retrying immediately can make the situation worse.

Suppose a server is overloaded. If your scraper immediately retries every failed request, it creates additional traffic while the server is already struggling.

Exponential backoff increases the delay between retry attempts.

For example:

  • First retry: approximately 1 second.

  • Second retry: approximately 2 seconds.

  • Third retry: approximately 4 seconds.

We can add random jitter to these delays to prevent multiple clients from retrying at precisely the same time.

Create the following helper:

async def retry_delay(
    attempt: int,
    retry_after: str | None = None,
) -> float:
    if retry_after:
        try:
            return min(
                max(float(retry_after), 0.0),
                60.0,
            )
        except ValueError:
            pass

    base_delay = min(2 ** attempt, 30)

    jitter = random.uniform(0, 0.5)

    return base_delay + jitter

This function supports numeric Retry-After values, which specify a delay in seconds.

For simplicity, it doesn't parse HTTP-date values in Retry-After. A production implementation should support both formats when processing that header.

It also caps the delay to avoid waiting indefinitely.

Why exponential backoff?

Imagine that a website temporarily returns HTTP 503.

Instead of repeatedly sending requests every few milliseconds, exponential backoff gives the server time to recover.

The jitter adds a small random variation to the delay.

However, retries should remain bounded. If a website continues returning errors, the scraper should eventually stop and report the failure.

7. Implementing the Reliable HTTP Request Function

Now let's combine timeouts, rate limiting, retries, and proxy configuration.

Add the following function to scraper.py:

RETRYABLE_STATUS_CODES = {
    408,
    429,
    500,
    502,
    503,
    504,
}


async def fetch_page(
    client: httpx.AsyncClient,
    url: str,
) -> str | None:
    parsed_url = urlparse(url)

    if parsed_url.scheme not in {"http", "https"}:
        raise ValueError("Only HTTP and HTTPS URLs are supported")

    host = parsed_url.netloc

    for attempt in range(MAX_RETRIES + 1):
        await rate_limiter.wait(host)

        try:
            response = await client.get(url)

            if response.status_code in RETRYABLE_STATUS_CODES:
                if attempt == MAX_RETRIES:
                    logger.error(
                        "Maximum retries reached for %s: HTTP %s",
                        url,
                        response.status_code,
                    )
                    return None

                delay = await retry_delay(
                    attempt,
                    response.headers.get("Retry-After"),
                )

                logger.warning(
                    "HTTP %s for %s. Retrying in %.2f seconds",
                    response.status_code,
                    url,
                    delay,
                )

                await asyncio.sleep(delay)
                continue

            response.raise_for_status()

            return response.text

        except httpx.TimeoutException:
            logger.warning(
                "Request timed out: %s",
                url,
            )

        except httpx.NetworkError:
            logger.warning(
                "Network error while fetching: %s",
                url,
            )

        except httpx.HTTPStatusError as exc:
            logger.error(
                "Non-retryable HTTP error %s for %s",
                exc.response.status_code,
                url,
            )
            return None

        except httpx.RequestError:
            logger.exception(
                "Request failed for %s",
                url,
            )

        if attempt < MAX_RETRIES:
            delay = await retry_delay(attempt)

            logger.info(
                "Retrying %s in %.2f seconds",
                url,
                delay,
            )

            await asyncio.sleep(delay)

    logger.error("Failed to fetch page after retries: %s", url)

    return None

Let's look at the important details.

Request timeouts

Timeouts are configured on the HTTP client, which we'll create shortly.

This prevents the scraper from waiting indefinitely for a response.

Retryable status codes

The function retries selected HTTP responses that may indicate temporary problems.

It does not retry every error. For example, a 404 response is treated as a permanent failure for the current attempt.

Handling HTTP errors

response.raise_for_status() raises an exception for unsuccessful HTTP responses.

We catch non-retryable HTTP errors and log them rather than repeatedly requesting the same resource.

Handling network errors

Timeouts and network errors may be temporary, so the function retries them within the configured limit.

If all attempts fail, it returns None.

The caller can then decide whether to skip the page, record the failure, or schedule another scraping run.

A note about retry counts

MAX_RETRIES = 3 means the scraper can make up to four attempts: the initial request plus three retries.

This distinction is important when estimating the maximum number of HTTP requests a scraping job might generate.

8. Configuring Proxies Correctly

A proxy server acts as an intermediary between the scraper and the destination website.

The request follows this path:

Python Scraper
      |
      v
Proxy Server
      |
      v
Target Website
      |
      v
Proxy Server
      |
      v
Python Scraper

Proxies are useful in several legitimate situations:

  • Accessing external websites through a corporate network.

  • Routing requests through an approved outbound gateway.

  • Applying centralized network policies.

  • Accessing permitted resources from a specific network environment.

They should not be used to evade a website's access restrictions, bans, authentication requirements, or published scraping rules.

Configure a proxy using an environment variable

Our application already reads:

PROXY_URL = os.getenv("SCRAPER_PROXY_URL")

Now create the HTTP client:

def create_http_client() -> httpx.AsyncClient:
    headers = {
        "User-Agent": (
            "DevByteResearchBot/1.0 "
            "(contact: admin@example.com)"
        ),
        "Accept": "text/html,application/xhtml+xml",
    }

    return httpx.AsyncClient(
        headers=headers,
        timeout=httpx.Timeout(REQUEST_TIMEOUT),
        follow_redirects=True,
        proxy=PROXY_URL,
    )

Replace the example user agent and contact information with accurate details for your application.

If the website requires a different request format or content negotiation, configure the appropriate headers.

For local development without a proxy, leave SCRAPER_PROXY_URL unset.

To configure an authorized proxy on macOS or Linux:

export SCRAPER_PROXY_URL="http://proxy.example.com:8080"

Then run the scraper.

If your proxy requires credentials, use a secure secret-management mechanism and avoid placing credentials directly in source code or committing them to version control.

HTTPX supports proxy configuration through its client interface. Verify the configuration against the version installed in your project.

Important: A proxy does not guarantee access to a website, and it does not eliminate rate limits or access restrictions. If the destination refuses automated requests, investigate the site's policies or use an authorized API instead.

9. Extracting Data with Beautiful Soup

Fetching HTML is only the first step. We also need to extract useful information.

For this example, suppose we have permission to scrape a product listing page with HTML similar to the following:

<div class="product">
    <h2 class="product-title">Wireless Keyboard</h2>
    <span class="product-price">₹1,499</span>
</div>

We can extract the product name and price using CSS selectors.

Add the following function:

def parse_products(
    html: str,
    source_url: str,
) -> list[dict]:
    soup = BeautifulSoup(html, "html.parser")

    products = []

    product_elements = soup.select(".product")

    for element in product_elements:
        title_element = element.select_one(
            ".product-title"
        )

        price_element = element.select_one(
            ".product-price"
        )

        if not title_element or not price_element:
            logger.warning(
                "Skipping incomplete product on %s",
                source_url,
            )
            continue

        title = title_element.get_text(
            " ",
            strip=True,
        )

        price = price_element.get_text(
            " ",
            strip=True,
        )

        products.append({
            "title": title,
            "price": price,
            "source_url": source_url,
            "scraped_at": datetime.now(
                timezone.utc
            ).isoformat(),
        })

    return products

Why validate extracted fields?

Websites frequently change their HTML structure.

For example, a website might rename .product-price to .price-value after a redesign.

Without validation, your scraper might save incomplete records or fail unexpectedly.

The parser checks whether both required elements exist before creating a record.

It also uses get_text() to extract readable text rather than returning HTML elements.

Why store the source URL?

Recording the source URL helps you trace where each record came from.

The timestamp indicates when the information was collected.

This becomes particularly useful when you compare prices across multiple scraping runs.

For production systems, consider storing normalized numeric prices, currencies, product identifiers, and other structured fields rather than keeping every value as raw text.

10. Putting Everything Together

Let's create the main scraping function.

Add the following code to scraper.py:

async def scrape_urls(
    urls: list[str],
) -> list[dict]:
    all_products = []

    async with create_http_client() as client:
        for url in urls:
            logger.info("Scraping: %s", url)

            html = await fetch_page(
                client,
                url,
            )

            if html is None:
                logger.warning(
                    "Skipping failed URL: %s",
                    url,
                )
                continue

            products = parse_products(
                html,
                url,
            )

            logger.info(
                "Extracted %d products from %s",
                len(products),
                url,
            )

            all_products.extend(products)

    return all_products


async def main():
    urls = [
        "https://example.com/products",
    ]

    products = await scrape_urls(urls)

    output_file = "products.json"

    with open(
        output_file,
        "w",
        encoding="utf-8",
    ) as file:
        json.dump(
            products,
            file,
            ensure_ascii=False,
            indent=2,
        )

    logger.info(
        "Saved %d products to %s",
        len(products),
        output_file,
    )


if __name__ == "__main__":
    asyncio.run(main())

Replace the example URL with a page you are authorized to scrape and adjust the CSS selectors to match its HTML structure.

You now have a scraper that:

  1. Creates a reusable asynchronous HTTP client.

  2. Applies request timeouts.

  3. Waits between requests to the same host.

  4. Retries selected temporary failures.

  5. Supports an optional authorized proxy.

  6. Parses product information.

  7. Skips pages that cannot be fetched.

  8. Saves extracted records to a JSON file.

Run it using:

python scraper.py

If the target page contains the expected HTML, the script creates a products.json file.

The output will look similar to this:

[
  {
    "title": "Wireless Keyboard",
    "price": "₹1,499",
    "source_url": "https://example.com/products",
    "scraped_at": "2026-10-30T10:00:00+00:00"
  }
]

The timestamp shown here is illustrative; the script generates the actual timestamp when it runs.

11. Improving the Scraper for Concurrent Requests

Our current implementation processes URLs sequentially.

This is a sensible starting point because it makes request frequency easier to control and reduces the risk of overwhelming a website.

However, some workloads involve many independent URLs, and sequential processing can take a long time.

Python's asyncio allows you to run multiple I/O-bound operations concurrently.

Before introducing concurrency, remember that the rate limiter must remain active. Simply using asyncio.gather() on hundreds of URLs can generate an excessive number of simultaneous requests.

A bounded approach looks like this:

async def scrape_concurrently(
    urls: list[str],
    concurrency: int = 3,
) -> list[dict]:
    semaphore = asyncio.Semaphore(concurrency)

    async with create_http_client() as client:

        async def scrape_one(url: str):
            async with semaphore:
                html = await fetch_page(
                    client,
                    url,
                )

                if html is None:
                    return []

                return parse_products(
                    html,
                    url,
                )

        results = await asyncio.gather(
            *[
                scrape_one(url)
                for url in urls
            ]
        )

    return [
        product
        for group in results
        for product in group
    ]

The semaphore limits the number of URLs being processed concurrently to three.

The per-host rate limiter still controls the interval between request starts for each host.

These mechanisms serve different purposes:

  • Concurrency limit: Controls how many operations can be active at once.

  • Rate limiter: Controls how frequently requests start.

  • Timeout: Limits how long a request can take.

  • Retry policy: Determines what happens after a temporary failure.

For production use, be aware that this example creates one task per URL. For very large URL lists, use a bounded worker pool or queue instead of creating thousands of tasks at once.

Also, the in-memory rate limiter coordinates requests only within one Python process. Multiple scraper processes need shared coordination if they must obey a common host-wide rate limit.

12. Respecting robots.txt and Website Policies

A reliable scraper should consider whether automated access is permitted before requesting pages.

The robots.txt file communicates crawling preferences for automated agents. It is commonly available at a website's root path, such as /robots.txt.

Python provides the urllib.robotparser module for checking these rules.

Here's a simple example:

from urllib.robotparser import RobotFileParser
from urllib.parse import urlparse, urljoin


def is_allowed_by_robots(
    url: str,
    user_agent: str,
) -> bool:
    parsed = urlparse(url)

    robots_url = urljoin(
        f"{parsed.scheme}://{parsed.netloc}",
        "/robots.txt",
    )

    parser = RobotFileParser()
    parser.set_url(robots_url)
    parser.read()

    return parser.can_fetch(
        user_agent,
        url,
    )

You could call this function before scraping a URL:

if not is_allowed_by_robots(
    url,
    "DevByteResearchBot",
):
    logger.warning(
        "Skipping URL disallowed by robots.txt: %s",
        url,
    )
    return []

This example is synchronous and is intended to illustrate the concept. For a larger asynchronous scraper, fetch and cache robots.txt using your HTTP client rather than performing blocking network operations for every URL.

Handle robots.txt retrieval errors explicitly. If the file cannot be retrieved, do not automatically assume that scraping is permitted; follow the website's documented policies and your organization's rules.

Also remember that robots.txt is not an access-control mechanism and does not replace the website's terms of service, contractual requirements, or applicable law.

13. Common Web Scraping Problems and Solutions

Even with retries and rate limiting, scrapers can encounter unexpected conditions.

Problem 1: HTTP 429 responses

HTTP 429 indicates that the server is limiting request frequency.

Recommended solution:

  • Respect the Retry-After header when provided.

  • Reduce the request rate.

  • Avoid immediately resuming the previous request frequency.

  • Check whether the website publishes API quotas or crawling guidelines.

If requests continue receiving 429 responses, pause the job and investigate instead of repeatedly retrying.

Problem 2: HTML selectors stop working

Your scraper may return an empty list even though the page visibly contains products.

Recommended solution:

  • Inspect the returned HTML.

  • Verify that your CSS selectors still match.

  • Check whether the data is rendered by JavaScript.

  • Look for an official API or documented data feed.

If a page requires JavaScript execution, an HTTP client alone may not return the rendered content. Use an authorized browser automation tool when appropriate and permitted.

Problem 3: Requests time out

Slow servers or network problems can cause request timeouts.

Recommended solution:

  • Configure appropriate connection and read timeouts.

  • Retry temporary failures within a limited budget.

  • Record the failed URLs.

  • Investigate whether the destination is experiencing an outage.

Increasing the timeout indefinitely is rarely a good solution because it can tie up resources for too long.

Problem 4: Duplicate records appear

A scraper may revisit the same page or collect the same product in multiple runs.

Recommended solution:

Use a stable identifier, such as a product ID or canonical URL, to detect duplicates.

If you store data in a database, use a unique constraint or upsert operation where appropriate.

Problem 5: A proxy stops working

An authorized proxy can become unavailable because of network failures, expired credentials, or configuration changes.

Recommended solution:

  • Log proxy connection failures separately from destination HTTP errors.

  • Verify proxy availability and credentials.

  • Configure appropriate timeouts.

  • Stop or pause the job if the required proxy is unavailable.

Do not respond to access restrictions by automatically cycling through proxies to evade them.

14. Production Best Practices

A scraper that works locally may need additional safeguards before running continuously or handling thousands of URLs.

Use structured logging

Record information such as:

  • Requested URL.

  • HTTP status code.

  • Attempt number.

  • Request duration.

  • Number of extracted records.

  • Failure reason.

Avoid logging proxy credentials, authentication tokens, or unnecessary personal data.

Store failed URLs

Do not simply discard every failed page.

Save the URL and failure reason so that you can investigate it later.

A database table or structured JSON Lines file can be useful for recording scraping results and failures.

Make scraping jobs resumable

For long-running jobs, track which URLs have been completed.

If a process crashes, it should be possible to resume the remaining work without repeating every successful request.

Use a database for larger datasets

JSON files are convenient for small projects, but they become less suitable when the dataset grows or multiple jobs need to update records concurrently.

Consider PostgreSQL or another database when you need:

  • Deduplication.

  • Filtering and querying.

  • Historical price tracking.

  • Incremental updates.

  • Concurrent workers.

  • Reliable storage.

Schedule jobs carefully

A scheduler such as cron or a task queue can run the scraper periodically.

Avoid overlapping runs when one job may still be active. Use a distributed lock, job-state record, or scheduler-level concurrency control when necessary.

Monitor performance and failures

Track successful requests, failed requests, retry counts, response times, and extracted record counts.

A sudden increase in failures or a drop in extracted records may indicate that the website has changed or that your scraper is no longer operating correctly.

Keep dependencies updated

Use a tested dependency lockfile and regularly review security updates.

Avoid blindly upgrading production dependencies without testing, especially when HTTP client behavior is important to your scraping workflow.

Conclusion

Building a reliable web scraper in Python requires more than sending requests and extracting HTML.

You need to account for temporary network failures, HTTP errors, request frequency, proxy configuration, changing page structures, and data quality.

In this tutorial, we built a scraper using HTTPX and Beautiful Soup. We implemented request timeouts, bounded retries, exponential backoff, per-host rate limiting, optional proxy support, structured logging, and JSON output.

We also explored concurrent scraping, robots.txt, common failures, and production considerations.

The key is to make your scraper predictable rather than aggressive. Use retries for temporary failures, respect rate limits, validate extracted data, and stop when access is not permitted.

With these practices, you can build Python scraping jobs that are easier to maintain, easier to debug, and better suited to real-world data collection.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘