【发布时间】:2019-08-13 03:19:36
【问题描述】:
我需要检查响应是否为图像。
为了工作的需要,我需要生成可以存在或不存在的照片的url,并记录包含图像的url。
当生成的 url 不显示照片时,网站的响应是 html,而 body 是:
<body>No File Found</body>
还有response.status =200
响应标头对于图像和No File Found 的结果都没有有价值的信息
For instance
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Transfer-Encoding: chunked
Expires: 0
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
X-Frame-Options: AllowAll
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: *
Date: Tue, 13 Aug 2019 01:44:40 GMT
我发现检查响应是否是这种情况下的图像的方法是:
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")
我知道这不是一个优雅的解决方案,但在这种情况下它可以工作
问题
我的问题是,如果有另一种更优雅的方法来解决这个问题,那就不要使用try 来解决这个问题。
注意我不需要下载图片只需要记录有效的url
欢迎提出任何建议。
提前致谢!!!
【问题讨论】:
标签: image python-2.7 web-scraping scrapy