requests重试递归写法

2021-05-27  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读