python - 如何处理 request.head(url) 中的超时错误?

标签 python python-requests

脚本:

>>> import requests
>>> print(requests.head('https://knoema.com/BISDPPLS2016/bis-property-prices-long-series'))
<Response [200]>

>>> print(requests.head('https://beta.knoema.org/BISDPPLS2016/bis-property-prices-long-series'))
Connection to beta.knoema.org timed out.

我也尝试了下面,但同样的错误:

>>> print(requests.head('https://beta.knoema.org/IRFCL2016Jul', timeout=5))

如果 requests.head(url) 不存在或因任何原因未加载,我想停止它。如何实现这一目标?

最佳答案

您必须使用 try-catch 处理异常

try: 
    requests.head('https://beta.knoema.org/BISDPPLS2016/bis-property-prices-long-series')
except requests.exceptions.Timeout as e:
    print e

您还可以设置较大的超时时间,以避免由于连接速度慢而导致错误

requests.head('https://beta.knoema.org/BISDPPLS2016/bis-property-prices-long-series', \
               timeout=5)

这里超时是5秒

关于python - 如何处理 request.head(url) 中的超时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46016004/

相关文章:

python - 如何将请求(python)cookie保存到文件中?

python - 将嵌套字典传递给请求模块

python - Pandas 日期时间格式

python - 从 url 文本自动生成文件名

javascript - Python 提交带有请求的标签

python - '属性错误 : 'module' object has no attribute 'file' ' when using oauth2client with Google Calendar

python - 如何处理 Pyodide/STLite 中的请求?

python - 有没有办法使用 opencv 删除图像中少于两个邻居的像素?

python - 使用正则表达式匹配相同字符精确次数

python - 尝试写入行时出现“FieldMissingError”