zoukankan      html  css  js  c++  java
  • Python 图像下载解决图像损坏

    在下载图片的过程中,经常会发现图片损坏,下面提供了两种解决方法:

    方法一:

     if response.status_code == 200:
            print '=================================================='
            if not os.path.exists(dir_path):
                os.makedirs(dir_path)
            total_path = dir_path + '/' + file_name
          # 核心代码,比较请求返回数据的大小和请求反应头里面的大小
            if len(response.content) == int(response.headers['Content-Length']):
    # print total_path with open(total_path, 'wb') as f: for chunk in response.iter_content(1024): f.write(chunk) f.close() else: raise FError('图片加载不完全') else: raise FError('网络没有正常返回')

    方法二:

     response = requests.get(url=source_url, headers=headers,verify=False,proxies=proxies,timeout=15)
            if response.status_code == 200:
                if not os.path.exists(dir_path):
                    os.makedirs(dir_path)
                total_path = dir_path + '/' + file_name
    
                image = Image.open(BytesIO(response.content))
                image.save(total_path)
    
                print "图片保存到本地"
                return "1"
            else:
                print "图片没有保存到本地"

    这两张方法都下载了一千多张图片作为测试,没有发现下载的图片加载到一半,或者其他错误。

    记录下来,仅供以后参考使用。

  • 相关阅读:
    dirname basename 截取路径中的目录以及文件名
    Singleton 单例模板
    人生最后一个10年-白银时代
    自动填充英文字母序列
    关于最近使用文档的几个技巧
    关于最近使用文档的几个技巧
    The King of Excel Geek 0.1版本
    Tkinter 学习
    test
    检测电话号码的python程序(一)
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/8599992.html
Copyright © 2011-2022 走看看