Learn Scrapy · 8/13

Mastering Downloader Middlewares

7 min read

Welcome, intrepid web-scraping adventurers, to a deep dive into one of Scrapy's most powerful and, dare we say, magical components: Downloader Middlewares. If you've ever felt like your spiders are just a little too... vanilla, or that you're constantly getting blocked, then this guide is your ticket to leveling up your scraping game.

We're going to pull back the curtain and show you how to intercept and modify Scrapy's requests and responses. Think of it as being the bouncer at a very exclusive data nightclub. You get to decide who gets in, what they look like, and what they do.


1. The Role of Downloader Middlewares in Scrapy 🕵️‍♀️

The Problem: Out of the box, Scrapy is a fantastic and efficient scraper. But the web is a wild place. Websites can be finicky, employ anti-scraping measures, or require specific request formats. A plain Scrapy spider might get shown the door (or a 403 Forbidden page) pretty quickly.

The Solution: Downloader middlewares are the answer. They are a framework of hooks into Scrapy's request/response processing. It's a light, low-level system for globally altering Scrapy's requests and responses. In essence, they sit between the Scrapy engine and the downloader, which is responsible for fetching web pages.

Imagine your Scrapy spider wants to get information from a website. It sends a "request" to the Scrapy Engine. The Engine then hands this request off to the Downloader. The Downloader Middleware is like a series of checkpoints the request must pass through before it goes out to the internet. At each checkpoint, you can inspect the request, change it, or even stop it altogether. The same thing happens in reverse when the website sends back a "response".

Here's a simplified flow:

Engine -> Downloader Middlewares -> Downloader -> Website

And on the way back:

Website -> Downloader -> Downloader Middlewares -> Engine

What can you do with them?

  • Modify requests: Change headers, user-agents, and cookies before they are sent.
  • Handle proxies: Route your requests through different IP addresses.
  • Manage retries: Implement custom logic for when a request fails.
  • Process responses: Handle different types of responses before they reach your spider.
  • And so much more! The possibilities are vast.

2. Modifying Requests: Custom User-Agents and Headers 🎭

The Problem: Many websites block requests that don't look like they're coming from a real web browser. The default Scrapy User-Agent is a dead giveaway that you're a scraper.

The Solution: You can use a downloader middleware to change the User-Agent and other headers for every request your spider makes. This makes your scraper look more like a legitimate user.

Let's get our hands dirty!

First, you'll need to create a downloader middleware. In your Scrapy project, you'll find a middlewares.py file. This is where the magic happens.

Here's an example of a simple middleware to set a custom User-Agent:

python
# myproject/middlewares.py

class CustomUserAgentMiddleware:
    def process_request(self, request, spider):
        request.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'

Now, you need to activate this middleware in your settings.py file:

python
# myproject/settings.py

DOWNLOADER_MIDDLEWARES = {
   'myproject.middlewares.CustomUserAgentMiddleware': 543,
   'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, # Disable the default one
}

What's happening here?

  • We created a class CustomUserAgentMiddleware.
  • The process_request method is called for each request that goes through the download middleware. We're simply setting the User-Agent header on the request object.
  • In settings.py, we add our middleware to the DOWNLOADER_MIDDLEWARES dictionary. The number 543 is the order in which the middleware will be executed. Lower numbers are closer to the engine. We also disable the default UserAgentMiddleware by setting its value to None.

Industry Practice: Rotating User-Agents

Setting a single custom User-Agent is good, but rotating through a list of them is even better. This makes it much harder for websites to detect your scraper based on a repeating pattern. There are third-party libraries like scrapy-user-agents that provide a list of common user agents and rotate them for you.


3. Integrating Proxies to Avoid IP Bans 🕵️‍♂️

The Problem: If you send too many requests from the same IP address in a short period, a website might block you. This is a common anti-scraping technique.

The Solution: Use proxies! A proxy server acts as an intermediary between your scraper and the website. It forwards your requests, making them appear to come from the proxy's IP address. By rotating through a pool of proxies, you can distribute your requests across many different IPs and avoid getting banned.

Let's see it in action.

You can set a proxy for a single request using the meta attribute:

python
yield scrapy.Request(url, self.parse, meta={'proxy': 'http://proxy.example.com:8080'})

But doing this for every request is tedious. A downloader middleware is the perfect tool for managing proxies for your entire spider.

Here’s a basic proxy middleware:

python
# myproject/middlewares.py
import random

class ProxyMiddleware:
    def __init__(self, proxy_list):
        self.proxy_list = proxy_list

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            proxy_list=crawler.settings.get('PROXY_LIST')
        )

    def process_request(self, request, spider):
        proxy = random.choice(self.proxy_list)
        request.meta['proxy'] = proxy

And in your settings.py:

python
# myproject/settings.py

DOWNLOADER_MIDDLEWARES = {
   'myproject.middlewares.ProxyMiddleware': 750,
}

PROXY_LIST = [
    'http://proxy1.com:8000',
    'http://proxy2.com:8000',
    # Add more proxies here
]

Under the Hood:

  • The from_crawler class method is used to get the list of proxies from the settings.
  • In process_request, we randomly select a proxy from our list and assign it to the request.meta['proxy']. Scrapy's built-in HttpProxyMiddleware (which runs after our middleware) will then use this proxy for the request.

Fun Fact: Some proxy services offer "rotating proxies" where the IP address changes automatically with each request. This can simplify your middleware even further!


4. Handling Failed Requests and Custom Retries 🔄

The Problem: Requests can fail for many reasons: network issues, temporary server errors (like a 503 Service Unavailable), or even because a proxy is down. By default, Scrapy has a RetryMiddleware that will automatically retry failed requests for certain HTTP status codes.

The Solution: While the default RetryMiddleware is helpful, you might need more granular control. For example, you might want to retry on different status codes, implement a custom backoff strategy, or even try a different proxy after a failure.

Let's build a smarter retry middleware.

Imagine a scenario where a website sometimes returns a 200 OK status but the page content says "Please try again later". The default RetryMiddleware won't catch this because the status code is technically successful.

Here's how you could handle this with a custom middleware:

python
# myproject/middlewares.py
from scrapy.exceptions import IgnoreRequest

class CustomRetryMiddleware:
    def process_response(self, request, response, spider):
        if b"Please try again later" in response.body:
            # Reschedule the request to be downloaded again
            new_request = request.copy()
            new_request.dont_filter = True # Allow duplicate requests for retries
            return new_request
        return response

Don't forget to enable it in settings.py:

python
# myproject/settings.py

DOWNLOADER_MIDDLEWARES = {
   'myproject.middlewares.CustomRetryMiddleware': 550,
}

How it Works:

  • The process_response method is called for each response that comes back from the downloader.
  • We check if a specific phrase is in the response body.
  • If it is, we create a copy of the original request and return it. Scrapy will then reschedule this request to be downloaded again. dont_filter=True is important here to prevent Scrapy's duplicate filter from dropping the retried request.
  • If the phrase isn't found, we simply return the response to be processed by the spider.

An interesting tidbit: You can also use the process_exception method in a downloader middleware to handle exceptions that occur during the request-downloading process. This is useful for catching things like timeouts or DNS errors.


Keep Calm and Scrape On! 🧘

Mastering downloader middlewares is a significant step towards becoming a Scrapy pro. They give you the fine-grained control needed to tackle even the most challenging scraping projects. Start with these fundamentals, experiment, and soon you'll be building robust and resilient spiders that can navigate the complexities of the modern web with ease.

Happy scraping! 🚀


📚 Extra Reading & References

Challenge

Challenge Instructions

You are tasked with creating a comprehensive Scrapy Downloader Middleware to handle common anti-scraping measures. This middleware will be used in a project to scrape a protected website.

Your goal is to implement a single middleware class, AdvancedDownloaderMiddleware, that performs the following actions:

  1. User-Agent Rotation: For every outgoing request, it must randomly select a User-Agent from a list provided in the project settings and assign it to the request's User-Agent header.

  2. Proxy Rotation: For every outgoing request, it must randomly select a proxy URL from a list in the settings and assign it to the request's meta['proxy'] attribute.

  3. Custom Content-Based Retry: The target website sometimes returns a 200 OK status code, but the page content simply says "Access Denied. Please try again later.". Your middleware must inspect the body of every successful response. If this specific byte string is found, the middleware should schedule a retry for that request without it being filtered out by the duplicate request filter.

Complete the provided AdvancedDownloaderMiddleware class to implement this functionality. You will need to properly initialize the middleware with settings, and implement the logic within the process_request and process_response methods.

Expected result

Expected Output Description

Your final submission should be the completed Python code for the AdvancedDownloaderMiddleware class. A correct implementation will satisfy the following criteria:

  1. The from_crawler class method correctly retrieves the ROTATING_USER_AGENT_LIST and PROXY_LIST from crawler.settings and uses them to instantiate and return the middleware class.

  2. The process_request method is fully implemented to:

    • Set request.headers['User-Agent'] to a randomly chosen string from the self.user_agents list.
    • Set request.meta['proxy'] to a randomly chosen string from the self.proxies list.
  3. The process_response method is fully implemented to:

    • Return the response object unmodified if its status is not 200 or if it does not contain the specific denial text.
    • If response.status is 200 and b"Access Denied. Please try again later." is present in response.body, it must return a copy of the original request object, configured with dont_filter=True to ensure it gets re-queued for download.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.