需求是这样的
- 爬虫需要代理。
- 代理会过期需要动态更新。
- 代理有快有慢,有时失效,希望自动过期失效代理。
只前两点的话,放到redis里随机取就好了。第三点squid原生支持,并且速度快的代理优先级高。
所以配置好squid,把爬虫代理指向127.0.0.1:3128即可。
每次更新代理,动态更新squid配置文件,并重启。
首先安装squid
yum install squid
然后创建一个squid配置模板
cd /etc/squid
mv squid.conf.default squid.conf.example
每次拿到代理之后把代理设置成当前squid的 parent
由于有可能有相同ip,而端口不同的代理
会报错
squid[2260]: ERROR: cache_peer 120.xx.xx.32 specified twice
所以要在最后加上proxy的name
cache_peer 120.xx.xx.32 parent 80 0 no-query weighted-round-robin weight=2 connect-fail-limit=2 allow-miss max-conn=5 name=proxy-90
然后保存conf,并重启squid
更新配置文件的python代码
def update_squid_conf:
default_conf = open('/etc/squid/squid.conf.example' , 'r').read()
default_conf += 'cache_dir null /tmp\n'
proxy_list = response.json['data']['proxy_list']
for index in range(len(proxy_list)):
proxy_text = proxy_list[index]
proxy = proxy_text.split(':')
proxy_conf = "cache_peer " + proxy[0] + " parent " + proxy[1] + " 0 no-query weighted-round-robin weight=2 connect-fail-limit=2 allow-miss max-conn=5 name=proxy-" + str(index) + "\n"
default_conf += proxy_conf
conf = open('/etc/squid/squid.conf' , 'w')
conf.write(default_conf)
conf.close()
message = os.system('systemctl restart squid')
print message
调用后其实无输出。
由于配置了cache_dir null
所以log里会输出
2016/06/18 18:06:25| Creating missing swap directories
2016/06/18 18:06:25| No cache_dir stores are configured.
运行命令
tail -f /var/log/squid/squid.out
然后执行更新squid conf的python代码
如正确打印日志,说明重启squid成功。
由于使用的是pyspider
直接建立一个project,定时爬代理,并更新squid文件就可以了
网友评论