首页 > 解决方案 > 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 内容,而不是识别下载失败。

有没有办法确定文件没有下载?

标签: python-3.xpython-requests

解决方案


我在这个 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

推荐阅读