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的值来适应需求。

相关推荐
可触的未来,发芽的智生10 分钟前
触摸未来2025-10-25:蓝图绘制
javascript·python·神经网络·程序人生·自然语言处理
golang学习记10 分钟前
Go slog 日志打印最佳实践指南
开发语言·后端·golang
新手村领路人21 分钟前
python opencv gpu加速 cmake msvc cuda编译问题和设置
开发语言·python·opencv
dengzhenyue1 小时前
C# 初级编程
开发语言·c#
jf加菲猫1 小时前
条款20:对于类似std::shared_ptr但有可能空悬的指针使用std::weak_ptr
开发语言·c++
暴风鱼划水1 小时前
卡码网语言基础课(Python) | 19.洗盘子
python·算法
Gitpchy2 小时前
Day 23 机器学习管道 pipeline
python·机器学习
程序员小远2 小时前
使用Jmeter进行http接口测试
自动化测试·软件测试·python·测试工具·jmeter·http·接口测试
jf加菲猫2 小时前
条款21:优先选用std::make_unique、std::make_shared,而非直接new
开发语言·c++
消失的旧时光-19432 小时前
Kotlin 高阶函数在回调设计中的最佳实践
android·开发语言·kotlin