python:检查 jpg 的 url 是否存在 [英] python: check if url to jpg exists
本文介绍了python:检查 jpg 的 url 是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在python中,如何检查以.jpg结尾的网址是否存在?
In python, how would I check if a url ending in .jpg exists?
例如:http://www.fakedomain.com/fakeImage.jpg
谢谢
推荐答案
>>> 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
如果状态不是 200,则该资源在 URL 中不存在.这并不意味着它完全消失了.如果服务器返回 301 或 302,这意味着资源仍然存在,但位于不同的 URL.要更改处理这种情况的函数,只需将状态检查行更改为 return response.status in (200, 301, 302)
.
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)
.
这篇关于python:检查 jpg 的 url 是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文