使用requests库可实现带认证的文件下载,通过设置Authorization头和流式读取避免内存溢出;urllib适合简单场景;断点续传需用Range头实现。

如果您尝试通过Python程序从远程服务器获取文件,但直接访问链接无法自动保存,则可能是需要通过API接口进行身份验证或特定请求头设置。以下是实现文件下载功能的几种常用方法:
该方法利用requests发送HTTP GET请求获取文件数据,并将其写入本地文件系统。适用于大多数公开或需认证的API接口。
1、安装requests库:在命令行中执行 pip install requests。
2、发送GET请求并流式下载文件,避免内存溢出:
```python
import requests
url = "https://example.com/api/file"
headers = {"Authorization": "Bearer your_token"} # 若需要认证
response = requests.get(url, headers=headers, stream=True)
if response.status_code == 200:
with open("downloaded_file.zip", "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
else:
print(f"下载失败,状态码:{response.status_code}")
```
urllib是Python内置模块,无需额外安装,适合简单场景下的文件抓取。
立即学习“Python免费学习笔记(深入)”;
1、导入urllib模块并调用urlretrieve函数直接下载:
```python
import urllib.request
url = "https://example.com/api/file"
file_path = "downloaded_file.pdf"
try:
urllib.request.urlretrieve(url, file_path)
print("文件下载完成")
except Exception as e:
print(f"下载出错:{e}")
```
2、若接口需要携带请求头信息,可使用OpenerDirector机制自定义请求。
某些API要求OAuth、JWT或其他形式的身份验证,必须在请求中包含有效令牌才能获取资源。
1、获取有效的访问令牌(如通过登录API获得)并存储在变量中。
2、构造带有Authorization头的请求:
```python
import requests
auth_token = "your_jwt_or_oauth_token"
headers = {
"Authorization": f"Bearer {auth_token}",
"Accept": "application/octet-stream"
}
with requests.get("https://api.example.com/download/123", headers=headers, stream=True) as r:
r.raise_for_status()
with open("secure_file.dat", "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
```
对于大文件传输,网络中断可能导致下载失败,可通过记录已接收字节数实现断点续传。
1、检查本地是否存在部分下载的文件,并读取其大小作为起始位置。
2、在请求中设置Range头指定下载范围:
```python
import requests
file_url = "https://example.com/largefile.bin"
local_filename = "resume_download.bin"
resume_header = {}
temp_size = 0
if os.path.exists(local_filename):
temp_size = os.stat(local_filename).st_size
resume_header = {"Range": f"bytes={temp_size}-"}
with requests.get(file_url, headers=resume_header, stream=True) as r:
with open(local_filename, "ab") as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
```
以上就是Python调用API接口如何下载文件_Python调用API接口实现文件下载功能的代码示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号