python爬虫验证下载的图片是否损坏方法
一、最佳方法
使用PIL库的Image进行验证,简单明了
from PIL import Image
import io
import requests
def is_image_valid(resp):
try:
with Image.open(io.BytesIO(resp.content)) as img:
img.verify() # 验证图片是否有效
return True
except Exception as e:
print(f"download_image is damage. image_url:{url} error:{e}")
return False
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
}
resp = requests.get(url, headers=headers)
print(is_image_valid(resp))