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

使用Selenium获取指定class元素失败求助:返回空列表

解决Selenium获取指定类名元素返回空列表的问题

以下是针对代码问题的具体解决步骤和修改方案:

核心问题分析

直接调用driver.get()后立即查找元素,页面尚未完成渲染,目标元素还未加载到DOM中,导致返回空列表。此外旧版Selenium API的使用、元素可能嵌套在iframe中也是潜在原因。

1. 添加显式等待(最关键修复)

使用Selenium的显式等待机制,等待目标元素加载完成后再进行查找,避免因页面加载延迟导致的空结果。

首先需要导入等待相关模块:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

2. 替换过时的查找API

find_elements_by_class_name属于旧版API,已被弃用,建议使用By.CLASS_NAME配合显式等待的方式。

3. 检查并处理iframe(如果存在)

如果目标元素嵌套在<iframe>标签内,需要先切换到iframe上下文才能查找元素。

完整修改后的代码

import matplotlib.pyplot as plt, json, colorama
colorama.init(autoreset=True)

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

x = []
y = []

chromedriver = 'chromedriver.exe'

d = DesiredCapabilities.CHROME
d['loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(desired_capabilities=d)

URL = 'https://bloxflip.com/crash'

driver.get(URL)

try:
    # 若目标元素在iframe内,取消下方注释并调整iframe定位方式(比如id/name)
    # iframe = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'iframe')))
    # driver.switch_to.frame(iframe)
    
    # 最长等待15秒,直到目标元素出现
    target_elements = WebDriverWait(driver, 15).until(
        EC.presence_of_all_elements_located((By.CLASS_NAME, 'crash_crashGameCoefficient__M8rxs'))
    )
    
    print(f"成功找到 {len(target_elements)} 个目标元素")
    # 打印元素文本内容(如果需要)
    for elem in target_elements:
        print(elem.text)
finally:
    # 确保浏览器关闭
    driver.quit()

额外检查点

  • 确认类名准确性:用浏览器开发者工具(F12)定位目标元素,核对class属性是否与你使用的crash_crashGameCoefficient__M8rxs完全一致,避免复制时出现空格或拼写错误。
  • 检查页面动态渲染:部分网站使用React/Vue等框架动态生成元素,显式等待能有效应对这类场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:15:43