爬虫下载图片信息保存到本地文件夹下

def save_img(self,url, file_name, file_path='drug_specification'):
  # 保存图片到磁盘文件夹 file_path中,默认为当前脚本运行目录下的 book\img文件夹
  try:
    if not os.path.exists(file_path):
    print '文件夹', file_path, '不存在,重新建立'
    # os.mkdir(file_path)
    os.makedirs(file_path)
    # 获得图片后缀
    file_suffix = os.path.splitext(url)[1]
    # 拼接图片名(包含路径)
    filename = '{}{}{}{}'.format(file_path, os.sep, file_name['drug_name'].encode('utf-8'), file_suffix)
    # 下载图片,并保存到文件夹中
    urllib.urlretrieve(url, filename=filename)
  except IOError as e:
    print '文件操作失败', e
  except Exception as e:
    log = traceback.format_exc()
    print '错误 :', log

 

posted @ 2017-11-21 15:29  python许三多  阅读(4915)  评论(0编辑  收藏  举报