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

相关推荐
谷粒.2 小时前
Cypress vs Playwright vs Selenium:现代Web自动化测试框架深度评测
java·前端·网络·人工智能·python·selenium·测试工具
云和数据.ChenGuang3 小时前
Ascend C 核心技术特性
c语言·开发语言
kyle~5 小时前
C++---value_type 解决泛型编程中的类型信息获取问题
java·开发语言·c++
NiNi_suanfa8 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
小糖学代码8 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent9 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
妖灵翎幺9 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
Halo_tjn9 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
star _chen9 小时前
C++实现完美洗牌算法
开发语言·c++·算法
周杰伦fans10 小时前
pycharm之gitignore设置
开发语言·python·pycharm