检查图像的URL是否打开并且在Python中是否存在 [英] check if a URL to an image is up and exists in Python

查看:70
本文介绍了检查图像的URL是否打开并且在Python中是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个网站.我想从服务器检查用户提交的链接是否实际上是存在的图像.

I am making a website. I want to check from the server whether the link that the user submitted is actually an image that exists.

推荐答案

这是一种快速的方法:

它并没有真正验证它是否是图像文件,它只是根据文件扩展名进行猜测,然后检查该URL是否存在.如果您确实需要验证从url返回的数据实际上是图像(出于安全原因),则此解决方案将无法工作.

It doesn't really verify that is really an image file, it just guesses based on file extention and then checks that the url exists. If you really need to verify that the data returned from the url is actually an image (for security reasons) then this solution would not work.

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)

这篇关于检查图像的URL是否打开并且在Python中是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆