配置 settings.py 启用自定义 IP 代理中间件

  DOWNLOADER_MIDDLEWARES

    设置自定义 IP 代理中间件优先级高于系统 IP 代理中间件

DOWNLOADER_MIDDLEWARES = {
    'quotes.middlewares.QuotesDownloaderMiddleware': 543,
    # 'quotes.middlewares.UserAgentMiddlewares': 543,
}

 

收集可用的 IP 代理,构建 IP 代理池

  在 settings.py 中定义IP代理数组

IPPools = [
    {"ipaddr":"124.205.155.149:9090"},
    {"ipaddr":"119.23.79.199:3128"},
    {"ipaddr":"120.26.208.102:88"},
    {"ipaddr":"111.231.12.253:1080"},
]

    这些IP可以从这个几个网站获取:快代理代理66有代理西刺代理guobanjia。如果出现像下面这种提示:"由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败"或者是这种," 由 于目标计算机积极拒绝,无法连接。". 那就是IP的问题,更换就行了。

 

middlewares.py 中添加 UserAgentMiddlewares 类

  重写 process_request() 方法

    使用 random 库的 choice 方法随机从 IP 中选取代理 IP

    设置 request 的 meta 属性设置代理

    def process_request(self, request, spider):
        thisip = random.choice(IPPools)
        request.meta['proxy'] = 'http://' + thisip['ipaddr']
        print('this is ip:%s'%thisip['ipaddr'])

 

posted on 2019-10-25 14:56  淡然。  阅读(2715)  评论(0编辑  收藏  举报