此为第二步,将得到的代理进行清洗,将可用的入库
简单清洗程序
原理:多线程跑检测代理,源数据从数据库中取出,反正 Redis可每秒取数据11万次,一定要多线程,这里主要网络请求占用时间长,所以多线程,我也不知道多少是个多,自己试吧
import requests,threading,time
from redis import Redis
redis = Redis(host='127.0.0.1',db=7)
def wash_ip():
print('线程{}启动'.format(threading.current_thread().name))
while redis.llen('nowashhttp')>5:
i = str(redis.lpop('nowashhttp'))[2:-1]
print(i)
proxies = {'http': 'http://' + i,
'https': 'https://' + i}
test_url = 'https://www.baidu.com/'
try:
r = requests.get(test_url,proxies=proxies, timeout=15)
if r.status_code == 200:
print(i + '可用')
redis.sadd('validip',i)
except:
pass
if __name__ == '__main__':
for i in range(100):
threading.Thread(target=wash_ip).start()
存至数据库时使用 集合类型,因为直接去重,检测代理,时间大都花在网络请求上了,个人试多线程数量,感觉60跟100并无太大差异,但8和60差别就海了去了
检测结果
下一步,用flask写接口,个人感觉如果用Django的话写一个好看的界面出来,专门做一个及时响应代理资源站也是不错的,但爬虫工程师不需要界面,要的是能用,好用,快,多!