ProxyForge Download

Scrapy Proxy Rotation: Complete Setup Guide with Middleware

Scrapy Proxy Rotation: Complete Setup Guide with Middleware

If you’re working on web scraping projects using Scrapy, proxy rotation is essential for maintaining anonymity and avoiding being blocked by websites. This guide will walk you through setting up proxy rotation in Scrapy using middleware. We'll cover everything from understanding middleware to implementing a custom proxy rotation solution.

Introduction to Scrapy Middleware

Middleware in Scrapy allows you to hook into specific points of the request/response processing pipeline, enabling you to modify requests and responses as they pass through your spider. Proxy rotation involves changing the IP address used for making HTTP requests, which can be crucial for scraping websites that block repeated or suspicious activity from a single IP.

Setting Up Your Scrapy Project

Before diving into proxy rotation, ensure you have Scrapy installed and set up a basic project. If you haven't done so already, install Scrapy using pip:

pip install scrapy

Create a new Scrapy project with:

scrapy startproject myproject
cd myproject

Creating the Proxy Middleware

We'll create a custom middleware to handle proxy rotation. This middleware will select a proxy from a list and attach it to each request.

Step 1: Create the Middleware File

Create a new file named proxy_middleware.py in your project's middlewares directory. If this directory doesn't exist, you can create it:

mkdir myproject/middlewares
touch myproject/middlewares/proxy_middleware.py

Step 2: Write the Middleware Code

Add the following code to proxy_middleware.py:

import random

class ProxyMiddleware:
    # List of proxies to rotate through
    proxy_list = [
        'http://proxy1.example.com:8080',
        'http://proxy2.example.com:8080',
        # Add more proxies as needed
    ]

    def process_request(self, request, spider):
        # Randomly select a proxy from the list
        proxy = random.choice(self.proxy_list)
        
        # Set the selected proxy to the request's meta
        request.meta['proxy'] = proxy
        
        # Optionally log which proxy is being used
        spider.logger.info(f"Using proxy: {proxy}")

Step 3: Enable the Middleware

To use this middleware, you need to enable it in your Scrapy settings. Open settings.py and add the following lines:

DOWNLOADER_MIDDLEWARES = {
    'myproject.middlewares.proxy_middleware.ProxyMiddleware': 610,
}

The number 610 is the priority of the middleware; lower numbers mean higher priority.

Testing Your Proxy Rotation Setup

To ensure that your proxy rotation setup works, you can create a simple spider to test it. Here’s an example:

import scrapy

class TestSpider(scrapy.Spider):
    name = 'test'
    start_urls = ['http://httpbin.org/ip']

    def parse(self, response):
        # Extract the IP address from the JSON response
        ip_address = response.json().get('origin')
        
        # Log the current IP address
        self.logger.info(f'Current IP: {ip_address}')

Run your spider with:

scrapy crawl test

You should see log messages indicating which proxy is being used and the corresponding IP address returned by httpbin.org/ip. If everything is set up correctly, you should see different IP addresses each time you run the spider.

Handling Proxy Failures

Proxy rotation middleware should also handle scenarios where a proxy fails. You can add error handling to retry requests with a different proxy or remove failed proxies from the list.

Here’s an updated version of the process_request method with basic error handling:

def process_exception(self, request, exception, spider):
    # Log the exception and try using another proxy for this request
    spider.logger.error(f"Proxy {request.meta['proxy']} failed: {exception}")
    
    # Remove the failed proxy from the list (optional)
    self.proxy_list.remove(request.meta['proxy'])
    
    # Retry the request with a different proxy
    if self.proxy_list:
        new_proxy = random.choice(self.proxy_list)
        spider.logger.info(f"Retrying with proxy: {new_proxy}")
        request.meta['proxy'] = new_proxy

Add this method to your ProxyMiddleware class and ensure it's called by adding the following line to your settings:

DOWNLOADER_MIDDLEWARES = {
    'myproject.middlewares.proxy_middleware.ProxyMiddleware': 610,
}

Conclusion

Scrapy middleware is a powerful tool for extending the functionality of your web scraping projects. By implementing proxy rotation, you can improve the reliability and anonymity of your scrapers. The setup described in this guide provides a basic framework that you can expand upon based on your specific needs.

If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download. This tool can save time and effort by handling proxy management for you.

Free proxies break. ProxyForge doesn't.

The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.

Download ProxyForge free →