下载方法
import requests
import os
# 根据图片地址下载图片到本地
def download_image(url, save_path):
try:
# 发送HTTP GET请求获取图片内容
response = requests.get(url, stream=True)
response.raise_for_status() # 检查请求是否成功
# 确保保存路径存在
os.makedirs(os.path.dirname(save_path), exist_ok=True)
# 将图片内容写入本地文件
with open(save_path, 'wb') as file:
for chunk in response.iter_content(1024): # 分块写入
file.write(chunk)
print(f"图片已保存到 {save_path}")
except requests.exceptions.RequestException as e:
print(f"下载图片失败: {e}")