Pillow + scrapy = 有​​时无法识别图像文件

Pillow + scrapy = sometimes cannot identify image file

我对 scrapy 和 Pillow 有点小意见。知道他们有很多 "same" 问题,但我尝试了我找到的所有方法,但没有用..

我用scrapy解析了很多网站,超过10万个网页。 我创建了一个管道来定义页面是否包含图像,如果它下载图片并在同一路径上创建缩略图。使用它是因为如果创建缩略图失败,我有 "big" 版本的图像。

这里是一些代码

from PIL import Image
from slugify import slugify

class DownloadImageOnDisk( object ):
    def process_item( self, item, spider ):
        try:
            # If image on page
            if item[ 'image' ]:
                img     = item[ 'image' ]
                # Get extension of image
                ext     = img.split( '.' )
                ext     = ext[ -1 ].split('?')
                ext     = ext[0]
                key     = self.remove_accents( item[ 'imagetitle' ] ).encode( 'utf-8', 'replace' )
                path    = settings[ 'IMG_PATH' ] + item[ 'website' ] + '/' + key + '.' + ext

                # Create dir
                if not os.path.exists( settings['IMG_PATH'] + item['website'] ):
                    os.makedirs( settings[ 'IMG_PATH' ] + item[ 'website' ] )

                # Check if image not already exist
                if not os.path.isfile( path ):
                    # Download big image
                    urllib.urlretrieve( img, path )
                    if os.path.isfile( path ):
                        # Create thumb
                        self.optimize_image( path )

                item[ 'image' ] = item[ 'website' ] + '/' + key + '.' + ext

            return item
        except Exception as exc:
            pass

    # Slugify path
    def remove_accents( self, input_str ):
        try:
            return slugify( input_str )
        except Exception as exc:
            raise DropItem( exc )

    # Create thumb
    def optimize_image( self, path ):
        try:
            image = Image.open( path )
            image.thumbnail( ( 200,200 ), Image.ANTIALIAS )
            image.save( path, optimize=True, quality=85 )
        except IOError  as exc:
            raise DropItem( exc )
        except Exception as exc:
            raise DropItem( exc )

但有时,不规律(我认为是 100 件)我有这个错误

cannot identify image file '/PATH/NAME.jpg'

开启optimize_image功能。当我检查磁盘时,我的图像存在,它已经存在。

实在看不懂..

你有什么建议吗

提前致谢

不确定,但似乎可以通过

解决
import requests
import io
...
response = requests.get( img )
image = Image.open(io.BytesIO(response.content))
image.thumbnail( ( 200,200 ), Image.ANTIALIAS )
image.save( path, optimize=True, quality=85 )

我继续测试