Python requests下载文件的几种常用方法(附代码)

 更新时间:2025年03月05日 10:56:32   作者:microhex  
这篇文章主要介绍了五种下载方式的实现方法,包括基础下载、大文件分块下载、带有断点续传的下载、带有超时和重试的下载以及完整的下载器实现,文中给出了详细的代码示例,需要的朋友可以参考下

1. 基础下载:

import requests

def download_file(url, save_path):
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        with open(save_path, 'wb') as f:
            f.write(response.content)
        return True
    return False

# 使用示例
url = "https://example.com/file.pdf"
download_file(url, "file.pdf")


2. 大文件分块下载:

import requests
from tqdm import tqdm

def download_large_file(url, save_path):
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        file_size = int(response.headers.get('content-length', 0))
        
        # 显示进度条
        progress = tqdm(response.iter_content(chunk_size=8192), 
                       total=file_size,
                       unit='B', 
                       unit_scale=True)
        
        with open(save_path, 'wb') as f:
            for data in progress:
                f.write(data)
        return True
    return False

3. 带有断点续传的下载:

import requests
import os

def resume_download(url, save_path):
    # 获取已下载文件大小
    initial_pos = os.path.getsize(save_path) if os.path.exists(save_path) else 0
    
    # 设置 Header
    headers = {'Range': f'bytes={initial_pos}-'}
    
    response = requests.get(url, stream=True, headers=headers)
    
    # 追加模式打开文件
    mode = 'ab' if initial_pos > 0 else 'wb'
    with open(save_path, mode) as f:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                f.write(chunk)

4. 带有超时和重试的下载:

import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import time

def download_with_retry(url, save_path, max_retries=3, timeout=30):
    session = requests.Session()
    
    # 设置重试策略
    retries = Retry(total=max_retries,
                   backoff_factor=1,
                   status_forcelist=[500, 502, 503, 504])
    
    session.mount('http://', HTTPAdapter(max_retries=retries))
    session.mount('https://', HTTPAdapter(max_retries=retries))
    
    try:
        response = session.get(url, stream=True, timeout=timeout)
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
        return True
    except Exception as e:
        print(f"Download failed: {str(e)}")
        return False


5. 完整的下载器实现:

import requests
from tqdm import tqdm
import os
from pathlib import Path
import hashlib

class FileDownloader:
    def __init__(self, chunk_size=8192):
        self.chunk_size = chunk_size
        self.session = requests.Session()
        
    def get_file_size(self, url):
        response = self.session.head(url)
        return int(response.headers.get('content-length', 0))
    
    def get_file_hash(self, file_path):
        sha256_hash = hashlib.sha256()
        with open(file_path, "rb") as f:
            for byte_block in iter(lambda: f.read(4096), b""):
                sha256_hash.update(byte_block)
        return sha256_hash.hexdigest()
    
    def download(self, url, save_path, verify_hash=None):
        save_path = Path(save_path)
        
        # 创建目录
        save_path.parent.mkdir(parents=True, exist_ok=True)
        
        # 获取文件大小
        file_size = self.get_file_size(url)
        
        # 设置进度条
        progress = tqdm(total=file_size,
                       unit='B',
                       unit_scale=True,
                       desc=save_path.name)
        
        try:
            response = self.session.get(url, stream=True)
            with save_path.open('wb') as f:
                for chunk in response.iter_content(chunk_size=self.chunk_size):
                    if chunk:
                        f.write(chunk)
                        progress.update(len(chunk))
            
            progress.close()
            
            # 验证文件完整性
            if verify_hash:
                downloaded_hash = self.get_file_hash(save_path)
                if downloaded_hash != verify_hash:
                    raise ValueError("File hash verification failed")
                    
            return True
            
        except Exception as e:
            progress.close()
            print(f"Download failed: {str(e)}")
            if save_path.exists():
                save_path.unlink()
            return False
            
    def download_multiple(self, url_list, save_dir):
        results = []
        for url in url_list:
            filename = url.split('/')[-1]
            save_path = Path(save_dir) / filename
            success = self.download(url, save_path)
            results.append({
                'url': url,
                'success': success,
                'save_path': str(save_path)
            })
        return results

# 使用示例
downloader = FileDownloader()

# 单文件下载
url = "https://example.com/file.pdf"
downloader.download(url, "downloads/file.pdf")

# 多文件下载
urls = [
    "https://example.com/file1.pdf",
    "https://example.com/file2.pdf"
]
results = downloader.download_multiple(urls, "downloads")

总结 

到此这篇关于Python requests下载文件的几种常用方法的文章就介绍到这了,更多相关Python requests下载文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python 文本单词提取和词频统计的实例

    python 文本单词提取和词频统计的实例

    今天小编就为大家分享一篇python 文本单词提取和词频统计的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • python使用selenium模拟浏览器进入好友QQ空间留言功能

    python使用selenium模拟浏览器进入好友QQ空间留言功能

    这篇文章主要介绍了python使用selenium模拟浏览器进入好友QQ空间留言,在本文实现过程中需要注意的是留言框和发表按钮在不同的frame,发表在外面的一层,具体实现过程跟随小编一起看看吧
    2022-04-04
  • python基于opencv 实现图像时钟

    python基于opencv 实现图像时钟

    这篇文章主要介绍了python基于opencv 实现图像时钟的方法,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
    2021-01-01
  • python框架flask知识总结

    python框架flask知识总结

    今天带大家复习python框架的相关知识,文中对flask作了非常详细的介绍,对正在学习python的小伙伴们有很好的帮助,需要的朋友可以参考下
    2021-05-05
  • Python数据可视化之用Matplotlib绘制常用图形

    Python数据可视化之用Matplotlib绘制常用图形

    Matplotlib能够绘制折线图、散点图、柱状图、直方图、饼图. 我们需要知道不同的统计图的意义,以此来决定选择哪种统计图来呈现我们的数据,今天就带大家详细了解如何绘制这些常用图形,需要的朋友可以参考下
    2021-06-06
  • python递归打印某个目录的内容(实例讲解)

    python递归打印某个目录的内容(实例讲解)

    下面小编就为大家带来一篇python递归打印某个目录的内容(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • python 中赋值,深拷贝,浅拷贝的区别

    python 中赋值,深拷贝,浅拷贝的区别

    这篇文章主要介绍了python 中赋值,深拷贝,浅拷贝的区别,下文利用实例对三者进行详细的解析,具有一的的参考价值,需要的小伙伴可以参考一下,希望对你的学习有所帮助
    2022-03-03
  • python 错误处理 assert详解

    python 错误处理 assert详解

    这篇文章主要介绍了python 错误处理 assert详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Python3如何使用range函数替代xrange函数

    Python3如何使用range函数替代xrange函数

    这篇文章主要介绍了Python3如何使用range函数替代xrange函数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • 在Python中操作文件之truncate()方法的使用教程

    在Python中操作文件之truncate()方法的使用教程

    这篇文章主要介绍了在Python中操作文件之truncate()方法的使用教程,是Python入门学习中的基础知识,需要的朋友可以参考下
    2015-05-05

最新评论