在下面的代码中,如何测试类型是url还是类型是图像
for dictionaries in d_dict:
type = dictionaries.get('type')
if (type starts with http or https):
logging.debug("type is url")
else if type ends with .jpg or .png or .gif
logging.debug("type is image")
else:
logging.debug("invalid type")
Run Code Online (Sandbox Code Playgroud)
bob*_*nce 15
您无法从其URL中分辨出资源的类型.在没有.gif文件扩展名的URL上有一个GIF文件,或者有一个误导性的文件扩展名是完全有效的.txt.事实上,现在网页重写很受欢迎,你很可能会得到没有文件扩展名的图片网址.
它是Content-TypeHTTP响应标头,用于管理Web上的资源类型,因此您可以确定的唯一方法是获取资源并查看您获得的响应.您可以通过查看返回的标头来执行此操作urllib.urlopen(url).headers,但这实际上是获取文件本身.为了提高效率,您可能更喜欢制作不传输整个文件的HEAD请求:
import urllib2
class HeadRequest(urllib2.Request):
def get_method(self):
return 'HEAD'
response= urllib2.urlopen(HeadRequest(url))
maintype= response.headers['Content-Type'].split(';')[0].lower()
if maintype not in ('image/png', 'image/jpeg', 'image/gif'):
logging.debug('invalid type')
Run Code Online (Sandbox Code Playgroud)
如果你必须尝试根据URL路径部分中的文件扩展名来嗅探类型(例如,因为你没有网络连接),你应首先解析URL urlparse以删除任何?query或#fragment部分,这样http://www.example.com/image.png?blah=blah&foo=.txt就不会混淆它.您还应该考虑使用mimetypes将文件名映射到Content-Type,这样您就可以利用其对文件扩展名的了解:
import urlparse, mimetypes
maintype= mimetypes.guess_type(urlparse.urlparse(url).path)[0]
if maintype not in ('image/png', 'image/jpeg', 'image/gif'):
logging.debug('invalid type')
Run Code Online (Sandbox Code Playgroud)
(例如,使替代的扩展也是允许的.你应该至少是允许.jpeg的image/jpeg文件,以及突变的三个字母的Windows变化.jpg.)
使用正则表达式。
import re
r_url = re.compile(r"^https?:")
r_image = re.compile(r".*\.(jpg|png|gif)$")
for dictionaries in d_dict:
type = dictionaries.get('type')
if r_url.match(type):
logging.debug("type is url")
else if r_image.match(type)
logging.debug("type is image")
else:
logging.debug("invalid type")
Run Code Online (Sandbox Code Playgroud)
两点注释:type是内置的,也可以从 URL 加载图像。