最近写爬虫时,遇到一个响应接口响应速度太慢,由于对速度有要求,检查发现主要慢在了cookie的生成方面,于是就仿照IP池的轮询操作,编写了一个cookies池的轮询。
COOKIE_EXIST_MAX_TIME = 120 # 默认cookie存在时间 根据请求量设置大小
COOKIE_EXIST_COUNT = 30 # 设置列表中cookie存在的数量
def get_timestamp():
return str(int(time.time() * 1000))
def get_cookies2():
"""此处用来生成cookie"""
cookie = dict()
return cookie
class CookieInit(object):
def __init__(self):
# 初始化获取cookie
self.cookie_list = list()
while len(self.cookie_list) < 2:
# time.sleep(0.2) # todo 是否需要等待?
self.add_the_cookie()
logDebug(PROJECT, "##########cookie池初始化完成############")
print("##########cookie池初始化完成############")
# logDebug(PROJECT, f"{os.path.basename(__file__)} - {inspect.stack()[1][3]} - {sys._getframe().f_lineno} - 添加代理异常")
# 添加代理
def add_the_cookie(self):
try:
cookie = get_cookies2()
if cookie:
t = get_timestamp()
self.cookie_list.append((t, cookie))
except Exception:
logError(PROJECT, f"add_the_cookie 添加cookie池失败: \n {traceback.format_exc()}")
# 轮询代理
def round_the_cookie(self):
"""为了增加调用速度 此处不做检测操作"""
print("代理池COOKIE数量:%s" % len(self.cookie_list))
# logDebug(PROJECT, "代理池COOKIE数量:%s" % len(self.cookie_list))
try:
if len(self.cookie_list) == 0:
self.add_the_cookie()
cookie = self.cookie_list.pop()
self.cookie_list.insert(0, cookie)
return cookie
except Exception as e:
logError(PROJECT, f"round_the_cookie 轮询cookie池失败: \n {traceback.format_exc()}")
self.round_the_cookie()
# 删除代理
def delete_cookie(self, cookie):
try:
for t_del, pro_s_del in self.cookie_list:
if pro_s_del == cookie:
self.cookie_list.remove((t_del, pro_s_del))
print("删除成功")
return True
except Exception:
logError(PROJECT, f"delete_cookie 删除cookie池失败: \n {traceback.format_exc()}")
# error(f"{os.path.basename(__file__)} - {inspect.stack()[1][3]} - {sys._getframe().f_lineno} - 删除代理异常!, {traceback.format_exc()}")
return False
# 获取代理
def get_check_cookie(self):
avail_time, complete_cookie = self.round_the_cookie()
# todo 此处可同求检测cookie是否有效
return complete_cookie
# 检测代理有效时间
def check_cookie_time(self):
"""
此处对池中 时间和数量进行检验判断
也可增加 根据网络请求判断cookie有效性的逻辑
"""
while True:
print("#########异步检测COOKIE进行中###########")
logDebug(PROJECT, "#########异步检测COOKIE进行中###########")
logDebug(PROJECT, "代理池COOKIE数量:%s" % len(self.cookie_list))
# 对cookie 列表进行 时间 有效性
delete_cookie_list = list()
for t, pro_s in self.cookie_list:
if time.time() - int(t) > COOKIE_EXIST_MAX_TIME:
delete_cookie_list.append((t, pro_s))
for t_del, pro_s_del in delete_cookie_list:
# 不能按照索引删出
for t, pro_s in self.cookie_list:
if t_del == t and pro_s_del == pro_s:
self.cookie_list.remove((t, pro_s))
self.add_the_cookie()
break
while len(self.cookie_list) < COOKIE_EXIST_COUNT:
time.sleep(random.random())
self.add_the_cookie()
time.sleep(random.uniform(6, 10)) # 随机每间隔6-10s检测一次
# 获取所有的代理IP
def get_all_cookie(self):
return self.cookie_list
def check_cookie_time():
"""动态检测代理的时间"""
check_c_t = cookie_init.check_cookie_time
t = threading.Thread(target=check_c_t)
t.start()
cookie_init = CookieInit()
check_cookie_time()
def get_cookie():
cookie = cookie_init.get_check_cookie()
if cookie != None:
return cookie
else:
get_cookie()
def delete_cookie(cookie):
"""删除成功返回True"""
status = cookie_init.delete_cookie(cookie)
if status:
return True
else:
return False
此处根据时间 进行增删cookie
还可根据 调用次数(需要记录调用数量)进行增删
或者根据两者同时记录 进行增删