美文网首页
Scrapy 使用代理

Scrapy 使用代理

作者: 小伙在杭州 | 来源:发表于2019-12-08 11:14 被阅读0次

    一、使用开放代理(没有用户名和密码)

     # 开放代理
     class IPProxyDownloadMiddleware():
         PROXIES = ['175.42.68.217:9999',
                '223.242.247.177:9999',
                ]
    
         def process_request(self, request, spider):
             proxy = random.choice(self.PROXIES)
             request.meta['proxy'] = proxy
    

    二、使用独享代理(有用户名和密码)

    # 独享代理,需要用户名和密码
    class IPProxyDownloadMiddleware(object):
        def process_request(self, request, spider):
            # 需要访问的网站是http就写http 如果是https就写https,前提是代理本身具有相匹配的协议
            proxy  = 'http://112.74.198.237:16816' 
            user_password = "用户名:密码"
            request.meta['proxy'] = proxy
            # 转成bytes
            b64_user_password = base64.b64encode(user_password.encode('utf-8'))
            # Basic后面要有空格
            request.headers['Proxy-Authorization'] = 'Basic ' + b64_user_password.decode('utf-8')
    

    三、setting设置

    开启下载中间件

    相关文章

      网友评论

          本文标题:Scrapy 使用代理

          本文链接:https://www.haomeiwen.com/subject/shcmgctx.html