Python:让 urllib 跳过失败的连接

发布于 2024-10-05 07:25:05 字数 124 浏览 0 评论 0 原文

使用诺基亚 N900 时,我有一个 urllib.urlopen 语句,如果服务器离线,我希望跳过该语句。 (如果连接失败>继续执行下一行代码)。

这应该/如何在 Python 中完成?

Using a Nokia N900 , I have a urllib.urlopen statement that I want to be skipped if the server is offline. (If it fails to connect > proceed to next line of code ) .

How should / could this be done in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暖风昔人 2024-10-12 07:25:05

根据 urllib 文档,如果无法建立连接。

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

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

According to the urllib documentation, it will raise IOError if the connection can't be made.

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

Edit: As unutbu pointed out, urllib2 is more flexible. The Python documentation has a good tutorial on how to use it.

So尛奶瓶 2024-10-12 07:25:05
try:
    urllib.urlopen("http://fgsfds.fgsfds")
except IOError:
    pass
try:
    urllib.urlopen("http://fgsfds.fgsfds")
except IOError:
    pass
温柔少女心 2024-10-12 07:25:05

如果您使用的是 Python3,urllib.request.urlopen 有一个 超时参数。您可以这样使用它:

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 还会引发 < code>urllib.error.URLError(也可以通过 request.URLError 访问)如果 url 不存在或者网络出现故障。

对于 Python2.6+,可以在此处找到等效代码

If you are using Python3, urllib.request.urlopen has a timeout parameter. You could use it like this:

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 is measured in seconds. The ultra-short value above is just to demonstrate that it works. In real life you'd probably want to set it to a larger value, of course.

urlopen also raises a urllib.error.URLError (which is also accessible as request.URLError) if the url does not exist or if your network is down.

For Python2.6+, equivalent code can be found here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文