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

相关推荐
武子康1 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
Petrichor_H_2 小时前
DAY 31 文件的规范拆分和写法
python
怪兽20142 小时前
fastjson在kotlin不使用kotlin-reflect库怎么使用?
android·开发语言·kotlin
ClearLiang2 小时前
Kotlin-协程的挂起与恢复
开发语言·kotlin
q***31832 小时前
爬虫基础之爬取某基金网站+数据分析
爬虫·数据挖掘·数据分析
彭同学学习日志2 小时前
Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘
android·开发语言·kotlin
海域云赵从友2 小时前
破解跨境数据传输瓶颈:中国德国高速跨境组网专线与本地化 IP 的协同策略
开发语言·php
咚咚王者2 小时前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
深蓝海拓3 小时前
使matplot显示支持中文和负号
开发语言·python
AntBlack4 小时前
AI Agent : CrewAI 简单使用 + 尝试一下股票分析
后端·python·ai编程