正在下载图片

时间:2010-02-22 09:10:30

标签: python

我使用了urllib2.build_opener()从相应的url.But下载图像以获取特定网址我收到错误。当我检查那个网址时,我看到没有图像。如何检查是否有图像?这是我的代码:

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 :(得分:1)

我不明白。为什么不用try和except关键字来捕获错误?

答案 1 :(得分: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

答案 2 :(得分:0)

选中exceptioncode属性。

答案 3 :(得分: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 - the missing manual