python - 验证 url 是否是没有 urllib.request.urlopen 的视频原始文件 link

python - Verify if a url is a video raw file link without urllib.request.urlopen

我想验证url是否是视频原始文件link,例如:

http://hidden_path/video_name.mp4

下面是我当前的代码:

def is_video(url):
    r = None
    try:
        r = urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}))
    except:
        return False
    content_type = r.getheader("Content-Type")
    if re.match("video*", content_type):
        return True
    return False

如果视频 url 是一个大视频,此代码将有问题,并且可能导致服务器超时错误。

有没有更好的方法?

如果您只想检查 header 的 Content-Type,您可以发送 HEAD 请求而不是 GET

HEAD 请求获得响应后,您可以在 Content-Type header 中检查 video,如上。

示例:

>>> req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
>>> r = urllib.request.urlopen(req)
>>> r.getheader('Content-Type')
'video/mp4'

希望如此

import mimetypes
url = 'http://media.theaterchurch.com/podcast/video/hd/720p/2016/05-08-16-720p.mp4'
print mimetypes.MimeTypes().guess_type(url)[0]

输出这个...

video/mp4