如何设置代理
为了实现代理,需要配置2个Middleware:
setting.py中定义:
SPIDER_MIDDLEWARES = {'project_name.middlewares.MyProxyMiddleware': 100,'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110}
其中100、110是执行的优先级,即我们自己定义的MyProxyMiddleware先执行,系统的HttpProxyMiddleware后执行。
我们自己的MyProxyMiddleware,主要负责向meta中写入代理信息
# Importing base64 library because we'll need it ONLY in case if the proxy we are going to use requires authenticationimport base64# Start your middleware classclass ProxyMiddleware(object):# overwrite process requestdef process_request(self, request, spider):# Set the location of the proxyrequest.meta['proxy'] = "http://YOUR_PROXY_IP:PORT"# Use the following lines if your proxy requires authenticationproxy_user_pass = "USERNAME:PASSWORD"# setup basic authentication for the proxyencoded_user_pass = base64.encodestring(proxy_user_pass)request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass
如果你用的是socks5代理,那么对不起,目前scrapy还不能直接支持,可以通过Privoxy等软件将其本地转化为http代理。
当前内容版权归 piaosanlang 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 piaosanlang .