You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium无法下载图片问题求助:原可行的图片下载代码现失效

问题排查与修复方案

核心问题分析

你的代码主要存在以下几个问题:

  • CSS选择器错误:页面中的图片标签是<img>而非<image>,且多class选择器格式错误。正确的选择器应为.image.loaded(匹配同时拥有image和loaded两个class的<img>元素)。
  • 缺少元素等待:页面加载是异步的,直接调用find_element可能在元素未渲染完成时执行,导致找不到元素。
  • 请求被拦截:直接用requests.get请求图片URL时,缺少浏览器标识头,容易被网站反爬机制拦截。
  • 懒加载属性问题:部分网站会用data-src而非src存储图片真实地址,需要确认图片元素的属性。

修复后的代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests
from PIL import Image
from io import BytesIO

driver = webdriver.Firefox()
driver.get("https://anilist.co/search/anime?genres=Action&format=TV")

try:
    # 等待图片元素加载完成,最长等待10秒
    image_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "img.image.loaded"))
    )
    
    # 优先获取data-src(懒加载场景),没有则取src
    image_src = image_element.get_attribute("data-src") or image_element.get_attribute("src")
    
    # 模拟浏览器请求头,避免被拦截
    headers = {
        "User-Agent": driver.execute_script("return navigator.userAgent;")
    }
    response = requests.get(image_src, headers=headers)

    if response.status_code == 200:
        image = Image.open(BytesIO(response.content))
        image.save("imagen-1.jpg")
        print("下载成功")
    else:
        print(f"请求失败,状态码:{response.status_code}")
except Exception as e:
    print(f"执行出错:{str(e)}")
finally:
    driver.quit()

关键修复说明

  • 修正CSS选择器:使用img.image.loaded精准定位目标图片元素。
  • 添加显式等待:通过WebDriverWait确保元素渲染完成后再进行操作,避免元素未找到的错误。
  • 处理懒加载属性:先尝试获取data-src(很多网站懒加载图片用这个属性), fallback到src。
  • 模拟浏览器请求头:直接复用当前浏览器的User-Agent,降低被反爬拦截的概率。
  • 异常捕获:添加try-except块捕获执行过程中的错误,方便排查问题。

内容的提问来源于stack exchange,提问作者karen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 06:50:02