user257543 user257543 - 1 year ago 147
Python Question

python: check if url to jpg exists

In python, how would I check if a url ending in .jpg exists?



Answer Source
>>> import httplib
>>> def exists(site, path):
...     conn = httplib.HTTPConnection(site)
...     conn.request('HEAD', path)
...     response = conn.getresponse()
...     conn.close()
...     return response.status == 200
>>> exists('', '/fakeImage.jpg')

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download