Scrapy爬虫框架如何使用代理进行采集

234 阅读1分钟

在我们学习爬虫的时候会接触学习到很多的爬虫框架可以供我们选择,也学习了如何应对一些目标网站的反爬机制。那么我们今天就简单的交流下Python的Scrapy爬虫框架以及使用代理进行采集的方法,还有如何随机使用预先设好的user-agent来进行爬取的用法。

在程序里面代理的使用是比较简单的步骤,只需要几步,测试下代理是否通过就可以了。

#! -*- encoding:utf-8 -*-
        import base64            
        import sys
        import random

        PY3 = sys.version_info[0] >= 3

        def base64ify(bytes_or_str):
            if PY3 and isinstance(bytes_or_str, str):
                input_bytes = bytes_or_str.encode('utf8')
            else:
                input_bytes = bytes_or_str

            output_bytes = base64.urlsafe_b64encode(input_bytes)
            if PY3:
                return output_bytes.decode('ascii')
            else:
                return output_bytes

        class ProxyMiddleware(object):                
            def process_request(self, request, spider):
                # 代理服务器(产品官网 www.16yun.cn)
                proxyHost = "t.16yun.cn"
                proxyPort = "31111"

                # 代理验证信息
                proxyUser = "username"
                proxyPass = "password"

                request.meta['proxy'] = "http://{0}:{1}".format(proxyHost,proxyPort)

                # 添加验证头
                encoded_user_pass = base64ify(proxyUser + ":" + proxyPass)
                request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass                    

                # 设置IP切换头(根据需求)
                tunnel = random.randint(1,10000)
                request.headers['Proxy-Tunnel'] = str(tunnel)

关于使用随机user-agent,默认情况下scrapy采集时只能使用一种user-agent,这样容易被网站屏蔽,下面的代码可以从预先定义的user- agent的列表中随机选择一个来采集不同的页面。

# 添加验证头
                encoded_user_pass = base64ify(proxyUser + ":" + proxyPass)
                request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass                    

这里只是简单的交流下在爬虫程序中代理ip和随机ua的使用方式,不同的程序语言有偏差,有需要的小伙伴可以根据自己的需求进行调整测试。

若有收获,就点个赞吧