当前位置: 首页 > news >正文

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 = 0while 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 responseexcept requests.exceptions.Timeout:print(f"POST请求超时,正在进行第 {retries + 1} 次重试...")except requests.exceptions.RequestException as e:print(f"请求发生异常:{e}")retries += 1print("请求失败,达到最大重试次数。")return None#Python爬虫requests判断请求超时并重新get发送请求,
def send_request_get(url, max_retries=3, timeout=5):retries = 0while retries < max_retries:try:response = requests.get(url, timeout=timeout)if response.status_code == 200:# 请求成功,返回响应return responseexcept requests.exceptions.Timeout:print(f"GET请求超时,正在进行第 {retries + 1} 次重试...")except requests.exceptions.RequestException as e:print(f"请求发生异常:{e}")retries += 1print("请求失败,达到最大重试次数。")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的值来适应需求。

http://www.lryc.cn/news/138340.html

相关文章:

  • CSS中如何实现多列布局?
  • 【C++】string简单实用详解
  • opencv 进阶16-基于FAST特征和BRIEF描述符的ORB(图像匹配)
  • Unity 类Scene窗口相机控制
  • juc基础(三)
  • c语言函数指针和指针函数的区别,以及回调函数的使用。
  • 什么是服务端渲染?前后端分离的优点和缺点?
  • 【Java】优化重复冗余代码的8种方式
  • rabbitmq卸载重新安装3.8版本
  • MyBatis分页思想和特殊字符
  • 设计模式大白话——命令模式
  • [线程/C++(11)]线程池
  • VR防地质灾害安全教育:增强自然灾害知识,提高自我保护意识
  • Mybatis多对多查询案例!
  • Android OpenCV(七十五): 看看刚”转正“的条形码识别
  • 数据结构——布隆计算器
  • 金融学复习博迪(第6-9章)
  • 解决idea登录github copilot报错问题
  • 什么是Flex布局?请列举一些Flex布局的常用属性。
  • React + TypeScript + antd 常见开发场景
  • 前端基础踩坑记录
  • k8s删除pod镜像没响应marking for deletion pod TaintManagerEviction
  • Nginx 使用 lua-nginx-module 来获取post请求中的request和response信息
  • 【Opencv】三维重建之cv::recoverPose()函数(1)
  • Perl兼容正则表达式函数-PHP8知识详解
  • Python处理空值NaN
  • 软件机器人助力交通运输局数据录入,实现高效管理
  • 时序分解 | MATLAB实现基于SGMD辛几何模态分解的信号分解分量可视化
  • FinalShell报错:Swap file “.docker-compose.yml.swp“ already exists
  • 卷积过程详细讲解