requests实例4:图片的爬取与保存
requests实例4:图片的爬取与保存
代码框架:
1 # coding=gbk 2 import requests 3 import os 4 url = "http://image.nationalgeographic.com.cn/2017/0211/20170211061910157.jpg" 5 root = "D://pics//" 6 path = root + url.split('/')[-1] 7 try: 8 if not os.path.exists(root): 9 os.mkdir(root) 10 if not os.path.exists(path): 11 r = requests.get(url) 12 with open(path, 'wb') as f: 13 f.write(r.content) 14 f.close() 15 print("文件保存成功") 16 else: 17 print("文件已存在") 18 except: 19 print("爬取失败")