Skip to content

Instantly share code, notes, and snippets.

@KeyleXiao
Created April 24, 2024 02:21
Show Gist options
  • Save KeyleXiao/832de16b66e8d8c359f1ed15e40b108e to your computer and use it in GitHub Desktop.
Save KeyleXiao/832de16b66e8d8c359f1ed15e40b108e to your computer and use it in GitHub Desktop.
use python download img from url
# -*- coding: utf-8 -*-
import requests
import os
from datetime import datetime
import sys
def download_and_save_image(url, directory,image_formate):
# 获取当前日期和时间,用于命名文件
now = datetime.now()
filename = now.strftime("%Y-%m-%d-%H-%M-%S.") + image_formate
filepath = os.path.join(directory, filename)
try:
# 发送GET请求获取图片
response = requests.get(url, stream=True)
response.raise_for_status() # 如果请求失败则抛出异常
# 打开文件以二进制写入模式
with open(filepath, 'wb') as file:
# 将响应内容写入文件
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
print(f"Image downloaded and saved as {filename} in {directory}")
except requests.RequestException as e:
print(f"Error occurred while downloading image: {e}")
if __name__ == "__main__":
# 检查命令行参数数量
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Usage: python script_name.py <image_url> [directory_path]")
print("If [directory_path] is not provided, the current script directory will be used.")
sys.exit(1)
# 获取URL参数
url = sys.argv[1]
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "source", "uploads")
image_formate = "png"
# 获取目录参数,如果没有提供则使用当前脚本所在目录
if len(sys.argv) == 3:
image_formate = sys.argv[2]
# 检查目录是否存在,如果不存在则创建
if not os.path.exists(directory):
os.makedirs(directory)
# 下载并保存图片
download_and_save_image(url, directory,image_formate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment