#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import urllib2
import os
def save_img(img_url,file_name,file_path='img'):
#保存圖片到磁盤文件夾 file_path中,默認為當前腳本運行目錄下的 book\img文件夾
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)