Loading... 欢迎移步博主CSDN:[CSDN博客](https://blog.csdn.net/weixin_42327790/article/details/102688652) **原因:** requests.Session()中无异常处理类 ![image1.png](https://www.520315.xyz/usr/uploads/2023/03/4185233709.png) 改写: 注释下面这句后![image2.png](https://www.520315.xyz/usr/uploads/2023/03/736952693.png) 抛出异常语句则不会报错![image3.png](https://www.520315.xyz/usr/uploads/2023/03/2714159241.png) 想报错session可以采用下列该种方式 ```python class Request: #构造函数 def __init__(self): self.requests = requests.Session() def post_url(self,url, para, header='', t_out=3): """ 构造post请求 :param url: :param data: :param t_out: :return: """ # print('once:'+str(self.cookies)) t = 0 while t < max_retry: if t != 0: time.sleep(1) try: r = self.requests.post(url, data=para, timeout=4, headers=header)#, cookies=self.cookies) except requests.exceptions.Timeout as e: print("freebook连接超时....") # print(str(e)) t += 1 except requests.exceptions.ConnectionError as e: print("网络异常") # print(str(e)) t += 1 except requests.exceptions.HTTPError as e: print("返回了不成功的状态码") # print(str(e)) t += 1 except Exception as e: print("出现了意料之外的错误") print(str(e)) t += 1 else: t = max_retry + 1 # self.cookies.update(r.cookies) # 保存cookie # print('twice:'+str(self.cookies)) if t == max_retry: print("超过最大重试次数") return -1 else: return r #get请求 def get_url(self,url, parameters={}, t_out=3): """ :param url: get请求的连接 :param t_out: 超时时间,默认3秒 :param parameters: 参数 :return: response """ # print('onc:'+str(self.cookies)) t = 0 # print(max_retry) while t < max_retry: if t != 0: print(t) time.sleep(1) try: r = self.requests.get(url, params=parameters, timeout=t_out)#, cookies=self.cookies) except requests.exceptions.Timeout as e: print("连接超时....") # print(str(e)) t += 1 except requests.exceptions.ConnectionError as e: print("网络异常") # print(str(e)) t += 1 except requests.exceptions.HTTPError as e: print("返回了不成功的状态码") # print(str(e)) t += 1 except Exception as e: print("出现了意料之外的错误") print(str(e)) t += 1 else: t = max_retry + 1 # self.cookies.update(r.cookies) # 保存cookie # print('twi:'+str(self.cookies)) if t == max_retry: print("超过最大重试次数") return -1 else: return r ``` 创建Request对象调用相应的get或post方法即可!!! 最后修改:2023 年 03 月 19 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏