mirror of
https://github.com/Murasame-Dev/McStatus-Img.git
synced 2025-12-17 05:37:57 +00:00
Create BackgroundsGet.py
This commit is contained in:
parent
77fda32374
commit
5c576c811f
1 changed files with 43 additions and 0 deletions
43
BackgroundsGet.py
Normal file
43
BackgroundsGet.py
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
import httpx
|
||||||
|
import os
|
||||||
|
|
||||||
|
def download_image_with_httpx_auto_redirect(url, save_path):
|
||||||
|
"""
|
||||||
|
使用httpx库自动处理重定向下载图片
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url (str): 图片URL
|
||||||
|
save_path (str): 保存路径
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# httpx默认也会自动跟随重定向
|
||||||
|
with httpx.Client(follow_redirects=True) as client:
|
||||||
|
response = client.get(url, timeout=30.0)
|
||||||
|
|
||||||
|
# 检查状态码
|
||||||
|
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)
|
||||||
|
|
||||||
|
Background = response.content
|
||||||
|
|
||||||
|
print(f"图片已成功保存到: {save_path}")
|
||||||
|
print(f"最终URL: {response.url}") # 显示最终重定向后的URL
|
||||||
|
return Background
|
||||||
|
else:
|
||||||
|
print(f"请求失败,状态码: {response.status_code}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"下载失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 使用示例
|
||||||
|
if __name__ == "__main__":
|
||||||
|
image_url = "https://www.loliapi.com/acg/"
|
||||||
|
save_path = "images/downloaded_image.jpg"
|
||||||
|
download_image_with_httpx_auto_redirect(image_url, save_path)
|
||||||
Loading…
Add table
Add a link
Reference in a new issue