Scrapy的中间件(一)

本文介绍了Scrapy的中间件开发,包括代理、UA和Cookies中间件的实现。中间件用于在请求和响应之间定制数据处理,如更换代理IP、UA和管理Cookies。通过设置中间件,可以在请求前修改请求头和代理,以及处理登录状态,提升爬虫的灵活性和隐蔽性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要内容参考 《Python爬虫开发 从入门到实战》

中间件是Scrapy里面的一个核心概念。使用中间件可以在爬虫的请求发起之前或者请求返回之后对数据进行定制化修改,从而开发出适应不同情况的爬虫。“中间件”本质上就是在中途劫持数据,做一些修改再把数据传递出去。中间件主要用来辅助开发,

在Scrapy中有两种中间件:下载器中间件(Downloader Middleware)和爬虫中间件(Spider Middleware)。

下载器中间件 Downloader Middleware
Scrapy的官方文档中,对下载器中间件的解释如下。

下载器中间件是介于Scrapy的request/response处理的钩子框架,是用于全局修改Scrapy request和response的一个轻量、底层的系统。

其实就是:更换代理IP,更换Cookies,更换User-Agent,自动重试.

如果完全没有中间件,爬虫的流程如下图所示。
在这里插入图片描述
使用了中间件以后,爬虫的流程如下图所示。
在这里插入图片描述

开发代理中间件

在爬虫开发中,有时候每一次访问都需要随机选择一个代理IP来进行。中间件本身是一个Python的类,只要爬虫每次访问网站之前都先“经过”这个类,它就能给请求换新的代理IP,这样就能实现动态改变代理。在创建一个Scrapy工程以后,工程文件夹下会有一个middlewares.py文件:


from scrapy import signals

class Douban250SpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of th
### Scrapy 中间件的使用与定制 Scrapy中间件位于引擎和下载器之间,用于处理请求和响应。通过编写中间件可以实现诸如代理设置、重试机制等功能[^1]。 #### 使用内置中间件 要激活内置中间件,在项目的`settings.py`文件中找到`DOWNLOADER_MIDDLEWARES`字典并取消注释或添加相应的键值对来开启特定功能: ```python DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90, } ``` 上述代码片段启用了默认的重试中间件,并设置了其优先级为90。不同类型的中间件有不同的默认优先级;数值越低表示执行顺序越高。 #### 创建自定义中间件 创建个新的Python模块(例如 `myproject/middlewares.py`),在此处定义自己的Downloader Middleware类: ```python from scrapy import signals class MyCustomDownloaderMiddleware(object): @classmethod def from_crawler(cls, crawler): s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader. pass def process_response(self, request, response, spider): # Called with the response returned from the downloader. return response def process_exception(self, request, exception, spider): # Handle exceptions raised during downloading of requests. pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) ``` 此模板展示了最基本的结构,其中包含了四个主要方法:`process_request`, `process_response`, `process_exception` 和 `spider_opened`. 开发者可以根据需求修改这些函数的行为以满足具体应用场景的要求. 为了使新编写的中间件生效,同样需要将其加入到`settings.py`中的`DOWNLOADER_MIDDLEWARES`配置项下: ```python DOWNLOADER_MIDDLEWARES = { ... 'myproject.middlewares.MyCustomDownloaderMiddleware': 543, } ``` 这里指定了该中间件将在整个下载过程中处于第543位被执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值