python图片api爬虫下载代码
代码如下
1 import os 2 import requests 3 #api地址 4 url = "https://api.gmit.vip/Api/DmImg?format=image" 5 #root后面是图片下载后保存路径,如果是win就得加上盘符 6 root = "/Volumes/data/python/api.gmit.vip/data/" 7 a = int(input('输入爬取数量:')) 8 i = 1 9 while i <= a: 10 i += 1 11 surl = requests.get(url).url 12 path = root + surl.split("/")[-1] 13 try: 14 if not os.path.exists(root): 15 os.mkdir(root) 16 if not os.path.exists(path): 17 r = requests.get(surl) 18 with open(path, "wb") as f: 19 f.write(r.content) 20 f.close() 21 print("亮少提示;文件保存成功") 22 else: 23 print("miao~,存在同名文件") 24 except: 25 print("limo:✘存在异常错误") 26