Python爬虫requests判断请求超时并重新post/get发送请求
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_retries
和timeout
的值来适应需求。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2019-08-21 Thinkphp中js报错,Uncaught SyntaxError: Unexpected token }