【问题标题】:Download image with URL in python: gaierror在 python 中下载带有 URL 的图像:gaierror
【发布时间】:2020-08-01 02:00:52
【问题描述】:

我正在尝试在 python 中下载带有 URL 的图像,但不幸的是,我收到了一个错误,我不知道如何处理它。

我正在使用以下代码:

def dowload(url_img):
    try :
        r = requests.get(url_img)
        with open('a.jpg', 'wb') as f:
           f.write(r.content)
    except urllib2.HTTPError:
        print("Some Err")
    if os.path.exists("a.jpg"):
       os.remove("a.jpg")
    return img

图片的网址是:“http://cloudimages.youthconnect.in/wp-content/uploads/2015/07/539.jpg”

问题是我收到以下错误:

---------------------------------------------------------------------------
gaierror                                  Traceback (most recent call last)
/usr/lib/python3.6/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1324                 h.request(req.get_method(), req.selector, req.data, headers,
-> 1325                           encode_chunked=req.has_header('Transfer-encoding'))
   1326             except OSError as err: # timeout error

16 frames
gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)
/usr/lib/python3.6/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1325                           encode_chunked=req.has_header('Transfer-encoding'))
   1326             except OSError as err: # timeout error
-> 1327                 raise URLError(err)
   1328             r = h.getresponse()
   1329         except:

URLError: <urlopen error [Errno -2] Name or service not known>

我无法检查我是否收到状态代码 200,因为无法访问该站点。当我尝试打开连接时,我收到此错误。

如果有人可以解决这个问题,我将不胜感激。该网址来自我试图一张一张下载图像的VGGface数据集。

【问题讨论】:

  • 网址是否正确?
  • @IainShelvington 该 URL 来自 VGG 面部数据集,因此我必须一一访问这些 URL 并检查它们是否有效,如果它们有效然后下载图像。所以我不知道如何检查这样的 URL。通常我会检查响应或状态码,但这里的情况有所不同。
  • 您能抓住URLError 来处理URL 无效或站点不再存在的情况吗? DNS 查找不会返回该域的任何内容
  • @IainShelvington 如果我能捕捉到这样的异常,那么我会跳过该图像并返回任何内容。如您所见,该函数将 URL 作为参数,所以我有很多 URL。
  • 你已经抓到urllib2.HTTPError了,能不能不要再添加一个except块?

标签: python url


【解决方案1】:

好的,我使用简单的except: 语句解决了这个问题,因为我不需要知道异常的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    相关资源
    最近更新 更多