Image Scrapy:检查响应是否为图像

Image Scrapy:检查响应是否为图像,image,python-2.7,web-scraping,scrapy,Image,Python 2.7,Web Scraping,Scrapy,我需要检查响应是否为图像 对于工作的要求,我需要生成可以存在或没有的照片的url,并记录包含图像的url 当生成的url不显示照片时,当正文为: <body>No File Found</body> 我发现检查此案例的响应是否为图像的方法是: try : no_file_found = response.xpath("/html/body[contains(., 'No File Found')]") excep

我需要检查响应是否为图像

对于工作的要求,我需要生成可以存在或没有的照片的url,并记录包含图像的url

当生成的url不显示照片时,当正文为:

<body>No File Found</body> 
我发现检查此案例的响应是否为图像的方法是:

        try :
            no_file_found = response.xpath("/html/body[contains(., 'No File Found')]")
        except:
            photo_url = response.url
            photo = PhotoItem()

            photo['id'] = id
            photo['url'] = photo_url

            yield photo
因为当响应是图像时,行

no_file_found = response.xpath("/html/body[contains(., 'No File Found')]")
抛出此异常:

raise NotSupported("Response content isn't text")
我知道这不是一个优雅的解决方案,但在这种情况下它是有效的

问题

我的问题是,是否有其他更优雅的方法来解决这个问题,而不是使用
尝试
来解决这个问题

请注意,我不需要下载图像,只需要记录有效的url即可

欢迎提出任何建议


提前感谢

最简单的方法可能是只检查响应的类型:

from scrapy.http.response.text import TextResponse

if not isinstance(response, TextResponse):
    # it's probably an image; do image stuff
from scrapy.http.response.text import TextResponse

if not isinstance(response, TextResponse):
    # it's probably an image; do image stuff