欢迎移步博主CSDN:CSDN博客

原因: requests.Session()中无异常处理类
在这里插入图片描述

改写:
注释下面这句后
在这里插入图片描述

抛出异常语句则不会报错
在这里插入图片描述

想报错session可以采用下列该种方式

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方法即可!!!

最后修改:2020 年 12 月 19 日 01 : 07 PM
如果觉得我的文章对你有用,请随意赞赏