mirror of
https://github.com/N1ngYu/SaltBot.git
synced 2025-09-28 08:42:40 +08:00
45 lines
1.5 KiB
Python
45 lines
1.5 KiB
Python
import httpx
|
||
import os
|
||
import logging
|
||
from io import BytesIO
|
||
|
||
# 配置日志
|
||
logging.basicConfig(level=logging.INFO)
|
||
logger = logging.getLogger(__name__)
|
||
|
||
def download_image(url: str, save_path: str):
|
||
"""
|
||
使用 httpx 下载图片并保存到本地
|
||
:param url: 图片的 URL
|
||
:param save_path: 保存图片的本地路径
|
||
:return: 保存的文件路径或 None(失败时)
|
||
"""
|
||
try:
|
||
# 发起 HTTP GET 请求
|
||
with httpx.Client() as client:
|
||
response = client.get(url)
|
||
if response.status_code == 200:
|
||
# 确保保存路径的目录存在
|
||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||
# 保存图片到本地
|
||
with open(save_path, "wb") as f:
|
||
f.write(response.content)
|
||
logger.info(f"图片已保存到 {save_path}")
|
||
return save_path
|
||
else:
|
||
logger.warning(f"下载失败,状态码: {response.status_code}")
|
||
return None
|
||
except Exception as e:
|
||
logger.error(f"下载图片时发生错误: {e}")
|
||
return None
|
||
|
||
if __name__ == "__main__":
|
||
# 示例用法
|
||
image_url = input("请输入图片的 URL: ")
|
||
save_path = input("请输入保存路径(例如 E:/img/test.png): ")
|
||
|
||
result = download_image(image_url, save_path)
|
||
if result:
|
||
print(f"图片已成功保存到 {result}")
|
||
else:
|
||
print("下载图片失败,请检查 URL 和路径是否正确。") |