如何用Python和Selenium检测网站是否存在图片
检测指定图片链接是否存在的布尔判断实现方法
下面提供两种常用场景的实现方案,分别适用于后端(Python)和前端(JavaScript):
后端实现(Python)
通过发送HEAD请求获取响应头信息,无需下载完整图片,高效判断图片是否存在:
import requests def has_image(isbn): url = f"https://portal.dnb.de/opac/mvb/cover?isbn={isbn}" try: # 发送HEAD请求,允许重定向 response = requests.head(url, allow_redirects=True) # 验证状态码为200且响应内容为图片类型 return response.status_code == 200 and 'image' in response.headers.get('Content-Type', '') except requests.exceptions.RequestException: # 网络异常时返回False return False # 测试示例 print(has_image("9783442472352")) # 输出 True print(has_image("3499239663")) # 输出 False
注意事项
- 使用
HEAD请求比GET更高效,仅获取响应头而非完整图片内容 - 额外验证
Content-Type,避免网站返回200状态但实际是错误页面的情况 - 捕获所有请求异常,确保网络故障时返回正确的布尔值
前端实现(JavaScript)
通过创建Image对象监听加载状态,或使用fetch发送HEAD请求:
方法1:Image对象监听
function checkImageExists(isbn) { return new Promise((resolve) => { const img = new Image(); img.src = `https://portal.dnb.de/opac/mvb/cover?isbn=${isbn}`; // 图片加载成功则返回true img.onload = () => resolve(true); // 加载失败(如404、跨域)则返回false img.onerror = () => resolve(false); }); } // 测试使用 checkImageExists("9783442472352").then(exists => console.log(exists)); // 输出 true checkImageExists("3499239663").then(exists => console.log(exists)); // 输出 false
方法2:Fetch发送HEAD请求
async function checkImageExists(isbn) { try { const url = `https://portal.dnb.de/opac/mvb/cover?isbn=${isbn}`; const response = await fetch(url, { method: 'HEAD' }); // 验证响应正常且内容为图片类型 return response.ok && response.headers.get('Content-Type')?.includes('image'); } catch (error) { return false; } }
注意事项
- 前端直接请求可能遇到跨域限制,若目标网站未配置CORS,建议通过后端代理转发请求
Image对象的onerror会包含跨域错误,此时返回false,需根据实际场景判断是否是图片不存在导致的错误
内容的提问来源于stack exchange,提问作者Benedikt Faude
相关产品推荐
相关产品推荐

