2010-02-22 93 views
2

我使用urllib2.build_opener()從相應的url下載圖片。但是對於特定的網址,我收到錯誤消息。當我查看該網址時,我看到沒有圖像。我如何檢查是否有圖像?這是我的代碼:正在下載圖片

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 

如何檢查的圖像是存在的,與儲蓄的形象繼續嗎?

回答

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 
+0

由於....當我與上面的代碼測試它works..but這樣文件「/usr/lib/python2.5/httplib所示新的錯誤.py「,第860行,在endheaders中self._send_output()文件」/usr/lib/python2.5/httplib.py「,第732行,在_send_output self.send(msg)文件中」/ usr/lib/python2。 5/httplib.py「,第699行,發送self.connect()文件」/usr/lib/python2.5/httplib.py「,第683行,在connect raise socket.error,msg IOError:[Errno socket error ](110,'連接超時')我嘗試了wid Except IOError,但它不是固定的 – user244470 2010-02-22 10:34:05

+0

你是否正在使用url lib2?因超時而可能會引發urllib2.URLError?我還補充說, – 2010-02-22 11:25:27

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

+1

趕上?蟒蛇無法趕上! – 2010-02-22 09:44:18

+0

@Auurag,你說得對。最近Java太多了。修正了它:) – extraneon 2010-02-22 10:01:44

+0

謝謝....當我用上面的代碼測試它的工作原理..但是新的錯誤如下所示 文件「/usr/lib/python2.5/httplib.py」,行860,在endheaders self._send_output() 文件「/usr/lib/python2.5/httplib.py」,第732行,在_send_output中 self.send(msg) 文件「/usr/lib/python2.5/httplib.py 「,第699行,發送 self.connect() 文件」/usr/lib/python2.5/httplib.py「,第683行,連接 raise socket.error,msg IOError:[Errno socket error] (110,'連接超時') 我試過wid IOException但它不是固定的 – user244470 2010-02-22 10:32:02