Python:让urllib跳过连接失败

时间:2010-12-02 20:18:25

标签: python urllib

使用诺基亚N900,我有一个urllib.urlopen语句,如果服务器处于脱机状态,我希望将其跳过。 (如果无法连接>继续下一行代码。)

如何在Python中完成这项工作?

3 个答案:

答案 0 :(得分:3)

根据urllib文档,如果无法建立连接,则会引发IOError

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

修改:正如unutbu指出的那样,urllib2更灵活。关于如何使用它,Python文档有一个很好的tutorial

答案 1 :(得分:3)

如果您使用的是Python3,则urllib.request.urlopen具有timeout参数。您可以像这样使用它:

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

timeout以秒为单位。上面的超短值只是为了证明它有效。在现实生活中,你可能想要将它设置为更大的值。

如果网址不存在或网络已关闭,

urlopen也会引发urllib.error.URLError(也可以request.URLError访问)。

对于Python2.6 +,等效代码可以是found here

答案 2 :(得分:2)

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