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 "图片没有保存到本地"

 

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

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

 

posted @ 2018-03-19 10:05  淋哥  阅读(1424)  评论(0编辑  收藏  举报