下载图片

2 投票
4 回答
1270 浏览
提问于 2025-04-15 19:34

我使用了urllib2.build_opener()来从一个网址下载图片。但是在某个特定的网址上,我遇到了一个错误。当我查看那个网址时,我发现那里没有图片。我该如何检查是否有图片呢?这是我的代码:

opener1 = urllib2.build_opener()
page1=opener1.open(orginal)
my_picture=page1.read()

我遇到的错误是

  File "suitcase.py", line 120, in <module>
    get_suitcase()
  File "suitcase.py", line 96, in get_suitcase
    page1=opener1.open(orginal)
  File "D:\Program Files\Python\lib\urllib2.py", line 395, in open
    response = meth(req, response)
  File "D:\Program Files\Python\lib\urllib2.py", line 508, in http_response
    'http', request, response, code, msg, hdrs)
  File "D:\Program Files\Python\lib\urllib2.py", line 433, in error
    return self._call_chain(*args)
  File "D:\Program Files\Python\lib\urllib2.py", line 367, in _call_chain
    result = func(*args)
  File "D:\Program Files\Python\lib\urllib2.py", line 516, in http_error_default

    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found

我该如何检查是否有图片,然后继续保存那张图片呢?

4 个回答

0
try:
    page1=opener1.open(orginal)
except HTTPError, e:
    if e.code == 404: # Only one of the many possible errors...
        print "Resource does not exist"
    raise

my_picture=page1.read() 

另请查看 urllib2 - 缺失的手册

1

我不太明白。为什么不直接用try和except这两个关键词来捕捉错误呢?

1

正如其他人所建议的,捕获异常并检查代码,例如:

import urllib2

opener1 = urllib2.build_opener()
try:
    page1=opener1.open("http://www.google.com/nosuchimage")
    my_picture=page1.read()
except urllib2.HTTPError,e:
    if e.code == 404:
        print "no such image"
    else:
        print "error",e
except urllib2.URLError,e:
    print "URLError",e

撰写回答