Python:让 urllib 跳过失败的连接
使用诺基亚 N900 时,我有一个 urllib.urlopen
语句,如果服务器离线,我希望跳过该语句。 (如果连接失败>继续执行下一行代码)。
这应该/如何在 Python 中完成?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
使用诺基亚 N900 时,我有一个 urllib.urlopen
语句,如果服务器离线,我希望跳过该语句。 (如果连接失败>继续执行下一行代码)。
这应该/如何在 Python 中完成?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
根据 urllib 文档,如果无法建立连接。
编辑:正如unutbu指出的,
urllib2
更加灵活。 Python 文档有一个关于如何使用它的很好的教程。According to the urllib documentation, it will raise
IOError
if the connection can't be made.Edit: As unutbu pointed out,
urllib2
is more flexible. The Python documentation has a good tutorial on how to use it.如果您使用的是 Python3,
urllib.request.urlopen
有一个 超时参数。您可以这样使用它: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: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 aurllib.error.URLError
(which is also accessible asrequest.URLError
) if the url does not exist or if your network is down.For Python2.6+, equivalent code can be found here.