#!/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)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
  • 2022-02-22
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-26
  • 2021-12-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2021-09-05
相关资源
相似解决方案