如何从Python3 Requests超时异常中解析URL及指定错误片段
解析Requests超时异常中的特定错误片段与URL路径
方案一:正则表达式提取(推荐,兼容性强)
利用异常对象的字符串输出格式固定的特点,将异常转为字符串后用正则匹配目标内容,这种方式不依赖内部实现,适配多种超时异常类型(如ConnectTimeout、ReadTimeout)。
示例代码:
import re import requests target_domain = "https://10.10.10.92/custom.php" try: response = requests.get(target_domain, timeout=5) except requests.exceptions.Timeout as err: err_content = str(err) # 匹配目标错误片段与URL路径 match_result = re.search(r'Max retries exceeded with url: (/[^\s]+)', err_content) if match_result: error_fragment = match_result.group(0) url_path = match_result.group(1) print(f"提取的错误片段:{error_fragment}") print(f"提取的URL路径:{url_path}")
方案二:访问异常内部属性(依赖版本,谨慎使用)
Requests的超时异常基于urllib3的异常实现,可以通过遍历异常的内部属性获取原始错误信息,但该方式依赖库的内部结构,版本更新可能失效。
示例代码:
import re import requests target_domain = "https://10.10.10.92/custom.php" try: response = requests.get(target_domain, timeout=5) except requests.exceptions.ConnectTimeout as err: # 获取urllib3的原始异常对象 urllib3_exception = err.args[0] err_content = str(urllib3_exception) # 同样用正则提取目标内容 match_result = re.search(r'Max retries exceeded with url: (/[^\s]+)', err_content) if match_result: print(f"提取的错误片段:{match_result.group(0)}")
关键说明
- 正则表达式
r'Max retries exceeded with url: (/[^\s]+)'中,/[^\s]+用于匹配以/开头的URL路径,直到遇到第一个空格为止。 - 方案一无需区分具体超时异常类型,只要错误字符串包含目标片段即可提取,适用性更强。
内容的提问来源于stack exchange,提问作者BoredTech
相关产品推荐
相关产品推荐

