Skip to main content
Scrapy is a powerful framework for large-scale web scraping. The best way to manage proxies in Scrapy is by using a custom Downloader Middleware. This allows you to centralize your proxy logic and keep your spiders clean.

Step 1: Create the Proxy Middleware

First, let’s create a middleware that will attach our proxy credentials to every request.
  1. In your Scrapy project, open the middlewares.py file.
  2. Add the following class. It reads credentials from your settings.py and can be easily extended to handle dynamic parameters.
middlewares.py
This advanced middleware allows you to pass dynamic parameters (like -country-de) from your spider to the middleware using request.meta['proxy_username_params'].

Step 2: Configure settings.py

Now, let’s enable the middleware and add your credentials.
  1. Open your settings.py file.
  2. Add your base proxy credentials.
  3. Enable the Scrapy2extractProxyMiddleware in DOWNLOADER_MIDDLEWARES.
settings.py
Your basic setup is now complete! Any request from any spider in your project will now automatically use your 2extract.com proxy.

Real-World Example: Scraping Steam Specials

Now, let’s use the middleware we just created to scrape all discounted games from the Steam store. This spider is now much cleaner because all the proxy logic lives in the middleware.

The Spider (steam_specials_spider.py)

Notice how clean this spider is. It only focuses on scraping logic and passing dynamic parameters to the middleware.
spiders/steam_specials_spider.py
CSS Selectors change! Websites like Steam frequently update their design. The CSS selectors in this example are correct at the time of writing but may need to be updated in the future.

What This Example Demonstrates

  • Best Practice: The spider is clean and focused on what to scrape. The middleware handles how to connect. This is a robust and scalable approach.
  • Dynamic Control: The spider can easily change its geo-location or session for any request by simply changing the proxy_username_params value in the meta dictionary.
  • Code Reusability: The Scrapy2extractProxyMiddleware can now be reused by all spiders in your project without duplicating code.