python-3.x - python将文件下载到内存中并处理断开的链接
问题描述
我正在使用以下代码将文件下载到内存中:
if 'login_before_download' in obj.keys():
with requests.Session() as session:
session.post(obj['login_before_download'], verify=False)
request = session.get(obj['download_link'], allow_redirects=True)
else:
request = requests.get(obj['download_link'], allow_redirects=True)
print("downloaded {} into memory".format(obj[download_link_key]))
file_content = request.content
obj 是一个 dict,其中包含 download_link 和另一个指示我是否需要登录页面以创建 cookie 的键。
我的代码的问题是,如果 url 被破坏并且没有任何文件可供下载,我仍然会获取页面的 html 内容,而不是识别下载失败。
有没有办法确定文件没有下载?
解决方案
我在这个 url中找到了以下解决方案:
import requests
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('https://www.youtube.com/watch?v=9bZkp7q19f0')
# >> False
print is_downloadable('http://google.com/favicon.ico')
# >> True
推荐阅读
- javascript - 从 Node 中的 API 获取数据并将其存储以导出到 CSV
- css - 从网格文件上的变量文件访问变量时出错
- sql - sql声明一个整数列表而不使用循环
- c++ - 在鼠标挂钩中,车轮增量始终为 0
- qt - Windows x64 上的 Qt 6.1.2,从源代码配置构建时出现很多错误
- node.js - 反应和节点加载更多按钮与 Redux 状态
- reactjs - 从 IonModal 更新主页组件的状态得到 useEffect 错误
- python - Slurm:为调用共享内存并行程序和 MPI 程序的 Python 脚本分配资源
- javascript - focusout 在另一个输入中变得未定义
- hazelcast - Hazelcast 安全证书(声称该软件没有任何安全漏洞的证明证书)