2017-09-02 53 views
0

脚本:如何处理request.head(URL)错误超时错误 - 蟒蛇3.6

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

我想停止requests.head(URL)如果不存在,或者不加载任何原因,并通过不加载/ url的响应不存在。 脚本不应该浪费时间加载网址。如何实现这一目标?

回答

2

你必须使用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秒

+0

@ Arpit Solanki,谢谢,但它需要时间,我想设置时间,在5秒内它应该返回。如何实现这一点。 –

+0

你可以设置5秒的超时时间,如果超时没有完成,那么它会抛出超时异常。 @faithon –

+0

好的谢谢,将在此工作 –