2010-12-02 70 views

回答

3

按照urllib文件,它会提高IOError如果连接无法进行。

try: 
    urllib.urlopen(url) 
except IOError: 
    # exception handling goes here if you want it 
    pass 
else: 
    DoSomethingUseful() 

编辑:作为unutbu指出,urllib2更加灵活。关于如何使用它,Python文档有一个很好的tutorial

2
try: 
    urllib.urlopen("http://fgsfds.fgsfds") 
except IOError: 
    pass 
3

如果您使用的是Python 2.6或更高版本,则urllib2.urlopen的参数为timeout。你可以使用这样的:

import urllib2 
try: 
    response = urllib2.urlopen('http://google.com',timeout = 0.001) 
except urllib2.URLError as err: 
    print('got here') 
    # urllib2.URLError: <urlopen error timed out> 

timeout在几秒钟内进行测量。上面的超短期价值只是为了证明它的工作原理。在现实生活中,当然你可能会想要将它设置为更大的值。

如果URL不存在或网络出现故障,urllib2也会引发urllib2.URLError异常。

+0

我认为唯一正确的答案。 +1 – khachik 2010-12-02 21:11:34