当前位置 博文首页 > Python使用scrapy采集数据过程中放回下载过大页面的方法

    Python使用scrapy采集数据过程中放回下载过大页面的方法

    作者:pythoner 时间:2021-07-31 17:46

    本文实例讲述了Python使用scrapy采集数据过程中放回下载过大页面的方法。分享给大家供大家参考。具体分析如下:

    添加以下代码到settings.py,myproject为你的项目名称

    复制代码 代码如下:
    DOWNLOADER_HTTPCLIENTFACTORY = 'myproject.downloader.LimitSizeHTTPClientFactory'

    自定义限制下载过大页面的模块

    复制代码 代码如下:
    MAX_RESPONSE_SIZE = 1048576 # 1Mb
    from scrapy.core.downloader.webclient import ScrapyHTTPClientFactory, ScrapyHTTPPageGetter
    class LimitSizePageGetter(ScrapyHTTPPageGetter):
        def handleHeader(self, key, value):
            ScrapyHTTPPageGetter.handleHeader(self, key, value)
            if key.lower() == 'content-length' and int(value) > MAX_RESPONSE_SIZE:
                self.connectionLost('oversized')
    class LimitSizeHTTPClientFactory(ScrapyHTTPClientFactory):
         protocol = LimitSizePageGetter

    希望本文所述对大家的Python程序设计有所帮助。

    jsjbwy
    下一篇:没有了