下载并保存图片Python2.7

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import urllib2
import os

def save_img(img_url,file_name,file_path='img'):
#保存图片到磁盘文件夹 file_path中,默认为当前脚本运行目录下的 bookimg文件夹
try:
if not os.path.exists(file_path):
print '文件夹',file_path,'不存在,重新建立'
#os.mkdir(file_path)
os.makedirs(file_path)
#获得图片后缀
if 'jpeg' in img_url:
file_suffix = '.jpeg'
elif 'jpg' in img_url:
file_suffix = '.jpg'
elif 'png' in img_url:
file_suffix = '.png'
else:
file_suffix = '.jpeg'
#拼接图片名(包含路径)
filename = '{}{}{}{}'.format(file_path,os.path.sep,file_name,file_suffix)
#下载图片,并保存到文件夹中
response = urllib2.urlopen(img_url)
cat_img = response.read()
with open(filename, 'wb') as f:
f.write(cat_img)
except IOError as e:
print '文件操作失败',e
except Exception as e:
print '错误 :',e
save_img(img_url, file_name)
原文地址:https://www.cnblogs.com/shiluoliming/p/8489162.html