如何设置代理

为了实现代理,需要配置2个Middleware:

setting.py中定义:

  1. SPIDER_MIDDLEWARES = {
  2. 'project_name.middlewares.MyProxyMiddleware': 100,
  3. 'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110
  4. }

其中100、110是执行的优先级,即我们自己定义的MyProxyMiddleware先执行,系统的HttpProxyMiddleware后执行。

我们自己的MyProxyMiddleware,主要负责向meta中写入代理信息

  1. # Importing base64 library because we'll need it ONLY in case if the proxy we are going to use requires authentication
  2. import base64
  3. # Start your middleware class
  4. class ProxyMiddleware(object):
  5. # overwrite process request
  6. def process_request(self, request, spider):
  7. # Set the location of the proxy
  8. request.meta['proxy'] = "http://YOUR_PROXY_IP:PORT"
  9. # Use the following lines if your proxy requires authentication
  10. proxy_user_pass = "USERNAME:PASSWORD"
  11. # setup basic authentication for the proxy
  12. encoded_user_pass = base64.encodestring(proxy_user_pass)
  13. request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass

如果你用的是socks5代理,那么对不起,目前scrapy还不能直接支持,可以通过Privoxy等软件将其本地转化为http代理。