美文网首页
requests重试递归写法

requests重试递归写法

作者: 还是那个没头脑 | 来源:发表于2021-05-27 10:05 被阅读0次
    def getResponse(id, url, tries=0):
        """
        发起请求
        :param id:
        :param url:
        :return:
        """
        headers = {
            "User-Agent": str(UserAgent().random)
        }
        proxies = getProxy()
    
        try:
            response = requests.get(
                url,
                headers=headers,
                proxies=proxies,
                timeout=6)
            if response.status_code == 200:
                return response
            else:
                print(id, url, "状态码异常")
                return False
        except BaseException:
            maxTryNum = 3  # 重试的次数
            if tries < maxTryNum:
                tries += 1
                time.sleep(2)
                print(f'连接不成功,尝试第 {tries} 次重连')
                return getResponse(id, url, tries)
    
            print(id, url, f"Has tried {maxTryNum} times to access url {url}, all failed!")
            return False
    

    相关文章

      网友评论

          本文标题:requests重试递归写法

          本文链接:https://www.haomeiwen.com/subject/bcyrsltx.html