【发布时间】:2020-05-27 17:57:22
【问题描述】:
我目前有一些代码旨在尝试执行 URL 请求,如果抛出任何异常以确认它们并继续。
try:
x = requests.get(URL)
except requests.exceptions.Timeout:
print('timeout error, proceed to next URL')
except requests.exceptions.TooManyRedirects:
print('too many redirects, proceed to next URL')
except requests.exceptions.RequestException:
print('request exception, proceed to next URL')
但是,使用 try 语句,有时会请求一个 URL,并且请求会持续数小时,并且永远不会抛出 Timeout 异常。本质上,它会进入 try 并执行 requests.get(URL),然后它就会得到卡住。不知道为什么会这样。
我怎样才能让它捕捉到超时错误,这样它就不会被卡住,而是在指定的时间(比如 10 秒或其他时间)后继续运行?
编辑:这些 URL 是链接到实际网站的有效 URL,并且循环设置正确,这不是问题。
【问题讨论】:
-
尝试在请求中指定自定义超时时间,例如:requests.get(url, timeout=5.0)
标签: python python-requests timeoutexception