In python, how would I check if a url ending in .jpg exists?
>>> import httplib >>> >>> def exists(site, path): ... conn = httplib.HTTPConnection(site) ... conn.request('HEAD', path) ... response = conn.getresponse() ... conn.close() ... return response.status == 200 ... >>> exists('http://www.fakedomain.com', '/fakeImage.jpg') False
If the status is anything other than a 200, the resource doesn't exist at the URL. This doesn't mean that it's gone altogether. If the server returns a 301 or 302, this means that the resource still exists, but at a different URL. To alter the function to handle this case, the status check line just needs to be changed to
return response.status in (200, 301, 302).