如何修改Python请求脚本,实现请求超时10秒自动重试?
解决方案
我们可以利用requests库的timeout参数直接设置请求超时阈值,同时捕获超时异常,将状态码非200和请求超时两种情况都作为重试触发条件。修改后的代码如下:
import requests from requests.exceptions import Timeout # Defining Functions to use in the script def make_request(student_id): """ Makes a response for the student ID given, Keeps repeating it till it's a successful response. """ url = 'http://app1.helwan.edu.eg/Commerce/HasasnUpMlist.asp' # Base URL to our college website params = { 'z_dep': '=', 'z_st_name': 'LIKE', 'z_st_settingno': '=', 'x_st_settingno': f'{student_id}', 'x_st_name': '', 'z_gro': '=', 'x_gro': '', 'x_dep': '', 'z_sec': 'LIKE', 'x_sec': '', 'Submit': '++++حفظ++++' } while True: try: # 设置10秒超时,超过时限则抛出Timeout异常 response = requests.get(url, params=params, timeout=10) # 状态码为200时返回响应,否则继续重试 if response.status_code == 200: return response except Timeout: # 捕获超时异常,直接进入下一次循环重试 continue
关键修改说明
- 给
requests.get()添加timeout=10参数,让请求在10秒内未得到响应时自动触发超时异常 - 用
while True循环统一处理两种重试场景,替代原有的单一状态码判断逻辑 - 捕获
requests.exceptions.Timeout异常,遇到超时直接重试 - 仅当请求成功返回200状态码时,才退出循环并返回响应
内容的提问来源于stack exchange,提问作者Esmael Maher
相关产品推荐
相关产品推荐

