Step 1: Create the Proxy Middleware
First, let’s create a middleware that will attach our proxy credentials to every request.- In your Scrapy project, open the
middlewares.pyfile. - Add the following class. It reads credentials from your
settings.pyand 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.
- Open your
settings.pyfile. - Add your base proxy credentials.
- Enable the
Scrapy2extractProxyMiddlewareinDOWNLOADER_MIDDLEWARES.
settings.py
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
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_paramsvalue in themetadictionary. - Code Reusability: The
Scrapy2extractProxyMiddlewarecan now be reused by all spiders in your project without duplicating code.