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

使用Selenium Python点击CSV下载按钮,悬停类名变化无法定位如何解决

问题根源
  • find_element_by_class_name() 方法仅支持传入 单个类名,你传入带.拼接的多类名是CSS选择器的语法,方法不匹配导致定位失败:你传入export-button.is-csv.hovering时,Selenium会自动在开头拼接.,且把非.的分隔符识别为后代选择器,最终生成你报错里的错误选择器.export-button is-csv.hovering,自然找不到元素
  • 两个类名状态属于同一个按钮元素,不是父子层级关系,你不需要先定位原按钮再在其内部查找悬停后的元素
  • 你没有模拟鼠标悬停操作,按钮不会自动触发类名变更,也找不到带hovering的元素
解决代码

优先使用不需要模拟悬停的方案,更简单稳定,适配Google Colab的headless环境:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Colab专属Chrome配置,缺一不可
options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# 必须设置窗口大小,避免headless模式下视口过小导致元素不可见
options.add_argument('--window-size=1920,1080')

driver = webdriver.Chrome('chromedriver', options=options)
driver.get('https://www.rotowire.com/basketball/injury-report.php')

try:
    # 显式等待按钮可点击,比硬sleep稳定性高
    download_csv = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, '.export-button.is-csv'))
    )
    download_csv.click()
finally:
    # 等待下载完成后再关闭驱动,可根据网速调整时长
    time.sleep(3)
    driver.quit()

如果上述方案点击无响应,再使用模拟悬停的方案:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--window-size=1920,1080')

driver = webdriver.Chrome('chromedriver', options=options)
driver.get('https://www.rotowire.com/basketball/injury-report.php')

try:
    # 先定位初始状态的按钮
    download_csv = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '.export-button.is-csv'))
    )
    # 模拟鼠标悬停触发类名变更
    ActionChains(driver).move_to_element(download_csv).perform()
    # 等待悬停状态按钮可点击后点击
    hover_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, '.export-button.is-csv.hovering'))
    )
    hover_button.click()
finally:
    time.sleep(3)
    driver.quit()
注意事项
  • 多类名定位统一使用By.CSS_SELECTOR,每个类名前加.直接拼接即可,.export-button.is-csv对应同时包含这两个类的元素
  • 不要使用已废弃的find_element_by_*系列方法,统一用find_element(By.定位方式, 定位值)的写法,适配Selenium所有新版本
  • 下载的文件默认保存在Colab的当前工作目录,可通过!ls命令查看

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:45:05