Python:让urllib跳过失败的连接

2024-05-29 03:01:30 发布

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

使用诺基亚N900,我有一个urllib.urlopen语句,如果服务器脱机,我想跳过它。(如果连接失败,请转到下一行代码)。在

在Python中应该/可以如何做到这一点?在


Tags: 代码服务器语句urlliburlopenn900脱机
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以秒为单位。上面的超短值只是为了证明它是有效的。当然,在现实生活中,您可能会希望将其设置为更大的值。在

如果url不存在或您的网络已关闭,urlopen还会引发一个^{}(也可以作为request.URLError访问)。在

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

根据urllib文档,如果无法建立连接,它将引发IOError。在

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

编辑:正如unutbu指出的,urllib2更加灵活。Python文档对如何使用它有很好的tutorial。在

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

相关问题 更多 >

    热门问题