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

相关推荐
CC__xy18 分钟前
04 类型别名type + 检测数据类型(typeof+instanceof) + 空安全+剩余和展开(运算符 ...)简单类型和复杂类型 + 模块化
开发语言·javascript·harmonyos·鸿蒙
青衫客3623 分钟前
用 Python 实现一个“小型 ReAct 智能体”:思维链 + 工具调用 + 环境交互
python·大模型·llm·react
萤丰信息29 分钟前
技术赋能安全:智慧工地构建城市建设新防线
java·大数据·开发语言·人工智能·智慧城市·智慧工地
AI视觉网奇1 小时前
音频分类模型笔记
人工智能·python·深度学习
Pocker_Spades_A1 小时前
飞算JavaAI家庭记账系统:从收支记录到财务分析的全流程管理方案
java·开发语言
Ratten2 小时前
【Python 实战】---- 实现一个可选择、配置操作的批量文件上传工具(四)配置管理界面和逻辑实现
python
Ratten2 小时前
【Python 实战】---- 实现一个可选择、配置操作的批量文件上传工具(五)打包成 exe 应用
python
跟橙姐学代码2 小时前
写 Python 函数别再死抠参数了,这招让代码瞬间灵活
前端·python
CHEN5_022 小时前
【Java基础常见辨析】重载与重写,深拷贝与浅拷贝,抽象类与普通类
java·开发语言
Despacito0o2 小时前
C语言基础:变量与进制详解
java·c语言·开发语言