这是一位群友学习python后练手的一段代码,主要是针对随机图片api接口请求并下载图片,测试可用,搬运一下

代码如下

import os
import requests
#api地址
url = "https://api.gmit.vip/Api/DmImg?format=image"
#root后面是图片下载后保存路径,我用的是mac,如果是win就得加上盘符
root = "/Volumes/data/python/api.gmit.vip/data/"
a = int(input('输入爬取数量:'))
i = 1
while i <= a:
    i += 1
    surl = requests.get(url).url
    path = root + surl.split("/")[-1]
    try:
        if not os.path.exists(root):
            os.mkdir(root)
        if not os.path.exists(path):
            r = requests.get(surl)
            with open(path, "wb") as f:
                f.write(r.content)
                f.close()
                print("文件保存成功")
        else:
            print("存在同名文件")
    except:
        print("存在异常错误")