阿里云9.9元云服务器限时购买

Python爬虫requests判断请求超时并重新post/get发送请求

Python爬虫requests判断请求超时并重新post/get发送请求
在使用Python爬虫中,你可以使用requests库来发送网络请求。为了判断请求超时并重新发送请求,你可以设置一个超时时间,并在请求超时时捕获异常重新发送请求。

复制代码
import requests
#Python爬虫requests判断请求超时并重新post发送请求,proxies为代理
def send_request_post(url, data, headers , proxies , max_retries=3, timeout=5):
    retries = 0
    while retries < max_retries:
        try:
            # 去掉警告
            requests.packages.urllib3.disable_warnings()
            response = requests.post(url=url, json=data, headers=headers , verify=False, proxies=proxies,timeout=timeout)
            if response.status_code == 200:
                # 请求成功,返回响应
                return response
        except requests.exceptions.Timeout:
            print(f"POST请求超时,正在进行第 {retries + 1} 次重试...")
        except requests.exceptions.RequestException as e:
            print(f"请求发生异常:{e}")
        retries += 1

    print("请求失败,达到最大重试次数。")
    return None

#Python爬虫requests判断请求超时并重新get发送请求,
def send_request_get(url, max_retries=3, timeout=5):
    retries = 0
    while retries < max_retries:
        try:
            response = requests.get(url, timeout=timeout)
            if response.status_code == 200:
                # 请求成功,返回响应
                return response
        except requests.exceptions.Timeout:
            print(f"GET请求超时,正在进行第 {retries + 1} 次重试...")
        except requests.exceptions.RequestException as e:
            print(f"请求发生异常:{e}")
        retries += 1

    print("请求失败,达到最大重试次数。")
    return None
复制代码

 

复制代码
#示例:get获取代理ip
def get_ip():
    response = send_request_get('http:/xxxxxxxxxxxxxx/tip')
    if response:
        data = json.loads(response.text)
           proxies = {
         "http": "http://%(proxy)s" % {"proxy": data["ip"]}, 
         "https": "http://%(proxy)s" % {"proxy": data["ip"]}
            }
           return proxies
#示例post
send_request_post(url, data, headers, proxies)
复制代码

在上面的示例中,send_request_get函数接受一个URL作为参数,并可选地指定最大重试次数和超时时间。函数使用requests.get发送GET请求,并设置了超时时间为5秒。如果请求超时,会捕获requests.exceptions.Timeout异常,并输出重试信息。如果发生其他异常,会捕获requests.exceptions.RequestException并输出相关信息。

你可以调整max_retriestimeout的值来适应需求。

 
 
 
posted @   HIIT  阅读(559)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-08-21 Thinkphp中js报错,Uncaught SyntaxError: Unexpected token }
阿里云限时红包 最高 ¥ 2000 云产品通用红包,可叠加官网常规优惠使用
点击右上角即可分享
微信分享提示