zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python 网络教程大全之 03 如何优雅的判断url是否可以下载?

Python下载 如何 判断 可以 是否 大全 url
2023-09-11 14:18:32 时间

实战需求

如何优雅的判断url是否可以下载?

解决方案

import requests
url = 'https://ai2opencode.com/'
def is_downloadable(url):
    """
    Does the url contain a downloadable resource
    """
    h = requests.head(url, allow_redirects=True)
    header = h.headers
    content_type = header.get('content-type')
    if 'text' in content_type.lower():
        return False
    if 'html' in content_type.lower():
        return False
    return True
	
	

print(is_downloadable(url))

运行结果

text/html; charset=UTF-8