python下载网络文件到本地指定文件夹

 在Python中下载文件到本地指定文件夹可以通过以下步骤实现,使用requests库处理HTTP请求,并结合os模块处理文件路径:

import requests, os,datetime
from urllib.parse import urlparse,parse_qs

"""
获取request header信息,Cookie根据网址需要自己设定
"""
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7;application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Cookie': '132213213213213213',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}


def download_file(url, save_dir=None,file_name=None):
    """
    下载文件并保存到指定路径,,从网络路径中获取文件名,例如https://127.0.0.1:8000/web/file/5ed63734774b40d181fd96e1c58133d2.pdf

    :param url: 文件下载URL
    :param save_dir: 文件保存路径
    :param file_name: 文件名
    """
    try:
        if file_name is None:
            parse_url=urlparse(url)
            file_name=os.path.basename(parse_url.path)
            if not file_name:
                file_name="download_file_"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        if save_dir is None:
            save_dir=rf"C:\Users\Desktop\download_file"
        save_path=os.path.abspath(save_dir)
        file_path=os.path.join(save_path,file_name)

        if save_dir and not os.path.exists(save_dir):
            os.makedirs(save_dir, exist_ok=True)

        # 发起带流式传输的GET请求
        with requests.get(url, stream=True,headers=headers) as response:
            response.raise_for_status()  # 检查HTTP状态码

            # 分块写入文件
            with open(file_path, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:  # 过滤保持连接的空白块
                        file.write(chunk)

        print(f"文件下载成功,保存路径:{file_path}")
        return True
    except requests.exceptions.RequestException as e:
        print(f"网络请求失败:{str(e)}")
    except IOError as e:
        print(f"文件操作失败:{str(e)}")
    except Exception as e:
        print(f"未知错误:{str(e)}")

    return False


def download_file2(url, save_dir=None,file_name=None):
    """
        下载文件并保存到指定路径,从网络路径中获取文件名,例如https://127.0.0.1:8000/web/file/5ed63734774b40d181fd96e1c58133d2.pdf

        :param url: 文件下载URL
        :param save_dir: 文件保存路径
        :param file_name: 文件名
    """
    try:
        if file_name is None:
            parse_url = urlparse(url)
            file_name = os.path.basename(parse_url.path)
            if not file_name:
                file_name = "download_file_" + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        if save_dir is None:
            save_dir = rf"C:\Users\Desktop\download_file"
        save_path = os.path.abspath(save_dir)
        file_path = os.path.join(save_path, file_name)

        if save_dir and not os.path.exists(save_dir):
            os.makedirs(save_dir, exist_ok=True)

        response = requests.get(url, stream=True, headers=headers)
        response.raise_for_status()
        with open(file_path, 'wb') as file:
            file.write(response.content)
        return True
    except requests.exceptions.RequestException as e:
        print(f"网络请求失败:{str(e)}")
    except IOError as e:
        print(f"文件操作失败:{str(e)}")
    except Exception as e:
        print(f"未知错误:{str(e)}")

    return False


def download_file3(url, save_dir=None,file_name=None):
    """
        下载文件并保存到指定路径,从网络路径中query参数中获取文件名,例如https://127.0.0.1:8000/web/file?path=2025041616372016\\5ed63734774b40d181fd96e1c58133d2.pdf

        :param url: 文件下载URL
        :param save_dir: 文件保存路径
        :param file_name: 文件名
    """
    try:
        if file_name is None:
            parse_url = urlparse(url)
            # 从query参数中提取文件名
            query_params = parse_qs(parse_url.query)
            # 获取 path 参数的值,path可根据实际情况进行调整
            path_value = query_params.get('path', [''])[0]

            # 提取文件名(最后一个反斜杠后的部分)
            file_name = path_value.split('\\')[-1]
            if not file_name:
                file_name = "download_file_" + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        if save_dir is None:
            save_dir = rf"C:\Users\Desktop\download_file"
        save_path = os.path.abspath(save_dir)
        file_path = os.path.join(save_path, file_name)

        if save_dir and not os.path.exists(save_dir):
            os.makedirs(save_dir, exist_ok=True)

        response = requests.get(url, stream=True, headers=headers)
        response.raise_for_status()
        with open(file_path, 'wb') as file:
            file.write(response.content)
        return True
    except requests.exceptions.RequestException as e:
        print(f"网络请求失败:{str(e)}")
    except IOError as e:
        print(f"文件操作失败:{str(e)}")
    except Exception as e:
        print(f"未知错误:{str(e)}")

    return False

使用示例

# 示例1:自动从URL提取文件名
download_file(
    url="https://example.com/report.pdf",
    save_dir="./downloads"
)

download_file2(
    url="https://example.com/report.pdf",
    save_dir="./downloads"
)

# 示例2:自定义文件名
download_file(
    url="https://example.com/data?format=csv",
    save_dir="./data_files",
    file_name="dataset.csv"
)

download_file2(
    url="https://example.com/data?format=csv",
    save_dir="./data_files",
    file_name="dataset.csv"
)

# 示例3:从网络路径中query参数中获取文件名
download_file3(
    url="https://example.com/data?path=20250417\\example.csv",
    save_dir="./data_files",
    file_name="example.csv"
)

关键点说明

  1. 文件名处理

    • 默认从URL路径中提取文件名(如https://a.com/b.zip提取b.zip)。

    • 若URL不包含文件名(如以/结尾),则使用默认名称downloaded_file

    • 支持通过参数file_name自定义文件名。

    • 支持从URL路径的Query参数中获取文件名(如https://example.com/data?path=20250417\\example.csv提取example.csv)

  2. 路径处理

    • 使用os.path模块确保路径跨平台兼容。

    • 自动创建目标目录(若不存在)。

  3. 流式下载

    • 使用stream=True分块下载,避免大文件占用过多内存。

    • 通过iter_content逐块写入,提升可靠性。

  4. 异常处理

    • 捕获常见错误(如网络问题、权限不足)。

    • 使用response.raise_for_status()检查HTTP状态码。

  5. 扩展性

    • 支持自定义请求头(如模拟浏览器访问)。

    • 可调整chunk_size优化下载速度与内存占用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值