download_image.py 814 Bytes
Newer Older
liyang's avatar
liyang committed
1
import requests
2
import os
liyang's avatar
liyang committed
3

4

liyang's avatar
liyang committed
5
def download_image(url, save_path):
6
    """
7
    下载图片并保存到本地文件
8

9 10 11
    :param url: 图片的 URL 地址
    :param save_path: 图片保存的文件路径
    :return: 下载成功返回 True,下载失败返回 False
12
    """
13 14 15
    if os.path.exists(save_path):
        # print(f"图片文件已存在:{save_path}")
        return True
16

liyang's avatar
liyang committed
17 18 19 20 21
    response = ""
    try:
        response = requests.get(url, stream=True)
    except:
        return False
22

liyang's avatar
liyang committed
23 24 25 26 27
    if response.status_code == 200:
        with open(save_path, 'wb') as file:
            for chunk in response.iter_content(1024):
                file.write(chunk)
        # print(f"图片下载成功:{save_path}")
28
        return True
liyang's avatar
liyang committed
29
    else:
30
        # print(f"图片下载失败:{url}")
31
        return False