小智 12
这是适用于我的应用程序的最佳方法,同样基于之前的评论:
def is_url_image(image_url):
image_formats = ("image/png", "image/jpeg", "image/jpg")
r = requests.head(image_url)
if r.headers["content-type"] in image_formats:
return True
return False
Run Code Online (Sandbox Code Playgroud)
Mat*_*odd 10
这是一种快速的方法:
它并不真正验证它确实是一个图像文件,它只是根据文件扩展猜测,然后检查该URL是否存在.如果您确实需要验证从url返回的数据实际上是一个图像(出于安全原因),那么此解决方案将无法正常工作.
import mimetypes, urllib2
def is_url_image(url):
mimetype,encoding = mimetypes.guess_type(url)
return (mimetype and mimetype.startswith('image'))
def check_url(url):
"""Returns True if the url returns a response code between 200-300,
otherwise return False.
"""
try:
headers = {
"Range": "bytes=0-10",
"User-Agent": "MyTestAgent",
"Accept": "*/*"
}
req = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(req)
return response.code in range(200, 209)
except Exception:
return False
def is_image_and_ready(url):
return is_url_image(url) and check_url(url)
Run Code Online (Sandbox Code Playgroud)