Downloading Image
I used urllib2.build_opener() to download an image from a corresponding url.But for a particular url I am getting an error. When I checked that url, I saw that there is no image. How can I check whether there is an image or not? This is my code:
opener1 = urllib2.build_opener()
page1=opener1.open(orginal)
my_picture=page1.read()
The error i got is
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(*arg开发者_运维知识库s)
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
How do I check that an image is there and proceed with saving that image?
I don't understand. Why just not catch the error with the try and except keywords?
as others have suggested catch the exception and check for code e.g.
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
By checking the code
attribute of the exception.
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()
see also urllib2 - the missing manual
精彩评论