Python 下载的 11 种姿势,一种比一种高级!

在数据驱动的时代,掌握高效获取网络资源的技能至关重要。

Python,作为一门简洁而强大的语言,为我们提供了丰富的工具来下载文件,无论是简单的图片、网页,还是存储在云端的资源。

本文将带你深入浅出地学习如何使用 Python 下载文件,从基础模块到高级技巧,助你轻松应对各种下载场景。

1. Requests:简洁优雅的下载利器

requests 模块以其简洁易用的 API 成为 Python 下载文件的首选。只需几行代码,即可轻松下载文件。

import requests

url = 'https://www.example.com/myfile.zip'  # 文件 URL
response = requests.get(url)  # 发送 GET 请求

with open('myfile.zip', 'wb') as f:  # 打开文件以二进制写入模式
    f.write(response.content)  # 将响应内容写入文件
 

2. Wget:经典下载工具的 Python 封装

wget 是一个经典的命令行下载工具,Python 的 wget 模块对其进行了封装,提供了便捷的下载功能。

import wget

url = 'https://www.python.org/static/community_logos/python-logo-master-v3-TM.png'  # 文件 URL
wget.download(url, 'python-logo.png')  # 下载文件并指定保存路径
 

3. 挑战:下载重定向的文件

有些情况下,我们需要下载的文件 URL 会发生重定向。requests  模块可以轻松应对这种情况。

import requests

url = 'https://www.example.com/redirect'  # 重定向 URL
response = requests.get(url, allow_redirects=True)  # 允许重定向

with open('myfile.pdf', 'wb') as f:
    f.write(response.content)

通过将 allow_redirects 参数设置为 True,requests 会自动处理重定向,获取最终的文件内容。

4. 分块下载:应对大型文件

下载大型文件时,为了避免内存溢出,我们可以使用分块下载的方式。

import requests

url = 'https://www.example.com/largefile.pdf'
response = requests.get(url, stream=True)  # 以流式方式获取响应

with open('largefile.pdf', 'wb') as f:
    for chunk in response.iter_content(chunk_size=1024):  # 每次读取 1024 字节
        if chunk:
            f.write(chunk)
 

5. 并行下载:提升下载效率

当需要下载多个文件时,我们可以使用多线程或多进程来并行下载,提高效率。

import os
import time
from concurrent.futures import ThreadPoolExecutor

import requests

urls = [  # 文件 URL 列表
    ('file1.txt', 'https://www.example.com/file1.txt'),
    ('file2.jpg', 'https://www.example.com/file2.jpg'),
    ('file3.zip', 'https://www.example.com/file3.zip'),
]


def download_file(url, path):
    response = requests.get(url)
    with open(path, 'wb') as f:
        f.write(response.content)


start_time = time.time()

with ThreadPoolExecutor(max_workers=3) as executor:  # 创建线程池
    for url in urls:
        executor.submit(download_file, url[1], url[0])  # 提交下载任务

end_time = time.time()

print(f"下载完成,耗时:{end_time - start_time:.2f} 秒")
 

6. 下载进度条:实时追踪下载进度

使用 clint 模块,我们可以为下载过程添加进度条,实时追踪下载进度。

import requests
from clint.textui import progress

url = 'https://www.example.com/largefile.zip'
response = requests.get(url, stream=True)

total_length = int(response.headers.get('content-length'))

with open('largefile.zip', 'wb') as f:
    for chunk in progress.bar(response.iter_content(chunk_size=1024), expected_size=(total_length / 1024) + 1):
        if chunk:
            f.write(chunk)
 

7. Urllib:Python 内置的网络请求库

urllib 是 Python 内置的网络请求库,无需安装即可使用。

import urllib.request

url = 'https://www.example.com'
urllib.request.urlretrieve(url, 'index.html')  # 下载网页并保存为 index.html
 

8. 代理下载:保护隐私,突破限制

在某些情况下,我们需要使用代理服务器下载文件,例如保护隐私、突破网络限制等。

import urllib.request

proxy_handler = urllib.request.ProxyHandler({'http': 'http://your_proxy:port'})  # 设置代理
opener = urllib.request.build_opener(proxy_handler)
urllib.request.install_opener(opener)

url = 'https://www.example.com/file.zip'
urllib.request.urlretrieve(url, 'file.zip')
 

9. Urllib3:功能强大的网络请求库

urllib3 是 urllib 的升级版本,提供了更多功能,例如连接池、SSL 验证等。

import urllib3
import shutil

url = 'https://www.example.com'

http = urllib3.PoolManager()
response = http.request('GET', url)

with open('index.html', 'wb') as f:
    shutil.copyfileobj(response.data, f)
 

10. Boto3:下载 Amazon S3 文件

boto3 是 AWS 官方提供的 Python SDK,可以方便地操作 Amazon S3 等服务。

import boto3

bucket_name = 'your-bucket-name'  # 存储桶名称
file_name = 'your-file.txt'  # 文件名
download_path = 'downloaded_file.txt'  # 下载路径

s3 = boto3.client('s3')
s3.download_file(bucket_name, file_name, download_path)
 

11. Asyncio:异步下载,提升效率

asyncio 是 Python 3.4 版本引入的异步 IO 库,可以实现高效的异步下载。

import asyncio
import aiohttp

async def download_file(session, url):
    async with session.get(url) as response:
        content = await response.read()
        return content

async def main():
    urls = [
        'https://www.example.com/file1.txt',
        'https://www.example.com/file2.jpg',
        'https://www.example.com/file3.zip',
    ]

    async with aiohttp.ClientSession() as session:
        tasks = [download_file(session, url) for url in urls]
        results = await asyncio.gather(*tasks)

        for i, result in enumerate(results):
            with open(f'file{i+1}', 'wb') as f:
                f.write(result)

if __name__ == '__main__':
    asyncio.run(main())
 

总结

本文介绍了使用 Python 下载文件的各种方法,从基础模块到高级技巧,涵盖了大部分下载场景。希望本文能够帮助你更加高效地获取网络资源,在数据科学的道路上披荆斩棘!

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

途途途途

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值