【问题标题】:python urllib2 check for both Http error AND urlerrorpython urllib2 检查 Http 错误和 urlerror
【发布时间】:2017-07-20 12:59:03
【问题描述】:

这是我的问题:

我的脚本中有 8 个链接,这些链接会根据脚本的其他部分进行更改。在这个链接中,只有 1 个会实际打开我需要的文件,其他 7 个可能会引发 404 错误(http)或 10061 错误(连接被拒绝,所以 URLerror)。

我希望我的代码这样做:

如果错误是 404,什么也不做

如果错误为 10061,则什么也不做

如果 http.headers 有 content.type 'pdf',继续下载。

到目前为止我写的代码:

    try:
        response = urllib2.urlopen(link) 
    except urllib2.HTTPError, e:
        if e.code == 404:
            print '404'
    except urllib2.URLError, e:
            if '10061' not in e.args 
                #Download code here

【问题讨论】:

  • 您对这段代码有什么疑问/问题?

标签: python urllib


【解决方案1】:

嗯,看看你的代码,你想要实现的这 3 行应该是这样的:(未选中)

try:
    response = urllib2.urlopen(link) 
except urllib2.HTTPError, e:
    if e.code == 404:
        print '404'
except urllib2.URLError, e:
    if e.code == 10061:
        print '10061'
content_type = response.get_header('content.type', default=None)
if content_type == 'pdf':
     #Download code here

【讨论】:

  • 感谢您的回复,但我收到有关“if e.code == 10061”的无效语法
猜你喜欢
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多