在Scrapy中間件里面寫(xiě)ip代理池相關(guān)

import random
from collections import defaultdict

from scrapy import signals
from twisted.internet.error import ConnectionRefusedError, TimeoutError

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

    # 初始化數(shù)據(jù)
    def __init__(self, settings):
        self.settings = settings
        self.ips = settings.getlist("IPS")
        #錯(cuò)誤記錄   轉(zhuǎn)成字典結(jié)構(gòu)(value是int類(lèi)型) 默認(rèn)為0
        self.proxy_error_stats = defaultdict(int)

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        # 實(shí)例化的時(shí)候,把settings給init函數(shù)
        s = cls(crawler.settings)
        # 實(shí)例化的時(shí)候注冊(cè)了個(gè)信號(hào)
        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
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        # 加代理IP
        if "proxy" not in request.meta:
            proxy = random.choice(self.ips)
            # proxy = random.choice(self.cookies)
            # proxy = random.choice(self.headers)
            print(proxy, "---------------------------------")
            request.meta['proxy'] = proxy
        # else:
        #     print(request.meta["proxy"])
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        status_code = response.status
        if status_code in [403, 500, 404]:

            ip = request.meta["proxy"]
            # 統(tǒng)計(jì)某個(gè)IP的錯(cuò)誤次數(shù)
            self.proxy_error_stats[ip] += 1
            # 如果大于我們約定的五次,那就刪IP
            if self.proxy_error_stats[ip] > 5:
                # self.ips.remove(ip)
                self.remove_fail_ip(ip)
                # 去掉這個(gè)請(qǐng)求的meta的proxy
                del request.meta["proxy"]
            return request
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        # 當(dāng)出現(xiàn)跟代理IP有關(guān)系的異常的時(shí)候
        if isinstance(exception, (ConnectionRefusedError, TimeoutError)):

            # self.ips 去掉這個(gè)無(wú)效的IP
            ip = request.meta["proxy"]
            # self.ips.remove(ip)
            self.remove_fail_ip(ip)
            # 去掉這個(gè)請(qǐng)求的meta的proxy
            del request.meta["proxy"]
            # 重新安排下載
            return request

    def remove_fail_ip(self, ip):
        if ip in self.ips:
            self.ips.remove(ip)

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

注:另外要在settings里面加一個(gè)IPS列表,里面放代理ip

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類(lèi)型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,658評(píng)論 1 32
  • 在寫(xiě)爬蟲(chóng)的時(shí)候,經(jīng)常會(huì)遇到一個(gè)難題,就是反爬蟲(chóng)。反爬蟲(chóng)策略一般就是檢測(cè)user-agent,IP等等信息,辨別是機(jī)...
    愛(ài)折騰的胖子閱讀 825評(píng)論 0 2
  • 我們總是斗志昂揚(yáng)抱著書(shū)本,與書(shū)中的文字來(lái)一場(chǎng)邂逅,來(lái)一場(chǎng)思想的碰撞,總想著自己一直在奮斗的路上。可惜,我們總被各種...
    Amy平凡的夢(mèng)閱讀 223評(píng)論 0 0
  • 樓下小店,東西又貴又次,大人無(wú)力吐槽。奈何孩子喜歡呀。 和一個(gè)寶媽邊看孩子邊聊天。誰(shuí)知一不留神,她家娃就不見(jiàn)影子了...
    夏宇嫣_8335閱讀 583評(píng)論 0 4
  • 01 生活中,除了需要情商、智商、財(cái)商,我們還需要具備住商。住商是一個(gè)人思維、審美、財(cái)富運(yùn)用等能力的綜合體現(xiàn)。 0...
    小碗月牙閱讀 311評(píng)論 0 4

友情鏈接更多精彩內(nèi)容