admin管理员组

文章数量:1637858

彻底搞懂Scrapy的中间件(一):https://wwwblogs/xieqiankun/p/know_middleware_of_scrapy_1.html
彻底搞懂Scrapy的中间件(二):https://wwwblogs/xieqiankun/p/know_middleware_of_scrapy_2.html
彻底搞懂Scrapy的中间件(三):https://wwwblogs/xieqiankun/p/know_middleware_of_scrapy_3.html

在 Scrapy 中捕获并处理各种异常

[ Scrapy使用技巧 ] 如何在 Scrapy 中捕获处理各种异常https://blog.csdn/sc_lilei/article/details/80702449

重写 scrapy 中间件之 RetryMiddleware:https://blog.csdn/qq_33854211/article/details/78535963

彻底搞懂Scrapy的中间件(一)

中间件是Scrapy里面的一个核心概念。使用中间件可以在爬虫的请求发起之前或者请求返回之后对数据进行定制化修改,从而开发出适应不同情况的爬虫。

“中间件”这个中文名字和前面章节讲到的“中间人”只有一字之差。它们做的事情确实也非常相似。中间件和中间人都能在中途劫持数据,做一些修改再把数据传递出去。不同点在于,中间件是开发者主动加进去的组件,而中间人是被动的,一般是恶意地加进去的环节。中间件主要用来辅助开发,而中间人却多被用来进行数据的窃取、伪造甚至攻击。

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

下载器中间件

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

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

这个介绍看起来非常绕口,但其实用容易理解的话表述就是:更换代理IP,更换Cookies,更换User-Agent,自动重试。

如果完全没有中间件,爬虫的流程如下图所示。

使用了中间件以后,爬虫的流程如下图所示。

开发代理中间件

Scrapy 设置代理终极宝典:https://zhuanlan.zhihu/p/79067223

scrapy 切换代理    针对特定响应状态码,使用代理重新请求

HttpProxyMiddleware(HTTP 代理中间件):https://github/kohn/HttpProxyMiddleware
scrapy 爬虫的自动代理中间件:https://github/cocoakekeyu/autoproxy

获取免费代理, 主要抓的是大陆的高匿代理:https://github/kohn/HttpProxyMiddleware/blob/master/fetch_free_proxyes.py

scrapy 爬虫代理 --- 利用 crawlera 神器,无需再寻找代理IP:http://blog.csdn/xiao4816/article/details/50650075

在爬虫开发中,更换代理IP是非常常见的情况,有时候每一次访问都需要随机选择一个代理IP来进行。

中间件本身是一个Python的类,只是爬虫每次访问网站之前都要先“经过”这个类,它就能给请求换新的代理IP,这样就能实现动态改变代理。

创建 scrapy 工程:scrapy startproject <工程名>

创建完 Scrapy 工程以后( 这里创建的工程名为 AdvanceSpider ),工程文件夹下会有一个 middlewares.py 文件,打开以后其内容如下图所示:

Scrapy 自动生成的这个文件名称为 middlewares.py,名字后面的 s 表示复数,说明这个文件里面可以放很多个中间件。

middlewares.py 中有 2 个 Python类,每个类都代表一个中间件,代码如下:

# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy/en/latest/topics/spider-middleware.html

from scrapy import signals


class AdvancespiderSpiderMiddleware(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 Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class AdvancespiderDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downl

本文标签: 中间件scrapy