如何用Python将HTTP可访问的远程服务器图片复制到本地?
嘿,这事儿其实挺简单的!我给你分享两个实用又容易上手的Python方法,帮你把远程HTTP图片存到本地文件夹里:
方法一:使用
requests库(推荐) requests是Python里处理HTTP请求的神器,语法简洁,用起来特别顺手。
首先如果还没装这个库,先在终端里装一下:
pip install requests
然后看示例代码,我给你写了带异常处理的版本,更稳妥:
import requests import os def download_image(url, save_path): # 确保保存目录存在,不存在就创建 os.makedirs(os.path.dirname(save_path), exist_ok=True) try: # 发送GET请求获取图片内容,stream=True是为了大文件更高效 response = requests.get(url, stream=True) # 检查请求是否成功 response.raise_for_status() # 写入本地文件 with open(save_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) print(f"图片已成功保存到:{save_path}") except Exception as e: print(f"下载失败:{str(e)}") # 示例用法 image_url = "https://example.com/your-image.jpg" # 替换成你的图片URL local_path = "./local-images/my-image.jpg" # 替换成你想保存的本地路径 download_image(image_url, local_path)
方法二:使用Python标准库
urllib.request 如果不想装第三方库,用Python自带的urllib也能搞定,不用额外安装依赖:
import urllib.request import os def download_image(url, save_path): os.makedirs(os.path.dirname(save_path), exist_ok=True) try: # 直接用urlretrieve下载并保存 urllib.request.urlretrieve(url, save_path) print(f"图片已成功保存到:{save_path}") except Exception as e: print(f"下载失败:{str(e)}") # 示例用法 image_url = "https://example.com/your-image.jpg" local_path = "./local-images/my-image.jpg" download_image(image_url, local_path)
一些小提示:
- 一定要确认你有访问目标图片的权限,别碰有版权保护的内容哦;
- 如果要批量下载,把所有图片URL放进一个列表,循环调用上面的函数就行;
- 可以给请求加个超时时间,比如
requests.get(url, stream=True, timeout=10),避免程序一直卡着。
内容的提问来源于stack exchange,提问作者Deba
相关产品推荐
相关产品推荐

