一、最佳方法
使用PIL库的Image进行验证,简单明了
from PIL import Image
import io
import requestsdef is_image_valid(resp):try:with Image.open(io.BytesIO(resp.content)) as img:img.verify() # 验证图片是否有效return Trueexcept 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))