如何处理中的超时错误请求.head(url)错误python 3.6

2024-06-07 18:21:48 发布

您现在位置:Python中文网/ 问答频道 /正文

脚本:

>>>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.

Tried below as well, but same error
>>>print(requests.head('https://beta.knoema.org/IRFCL2016Jul', timeout=5))

我想停下来请求.head(url)如果它不存在或由于任何原因没有加载,并且通过响应如0表示不加载/url不存在。 脚本不应该浪费时间来加载url。如何做到这一点?在


Tags: httpsorg脚本urlpropertyrequestsheadlong
2条回答

必须使用try-catch处理异常

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

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

^{pr2}$

这里超时5秒

您应该使用try-except块来处理请求异常。这是关于这个的文档。。。在

http://docs.python-requests.org/en/master/_modules/requests/exceptions/

相关问题 更多 >

    热门问题