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

Selenium find_elements(By.CLASS_NAME)仅返回单个元素问题排查

问题解决:Selenium find_elements仅返回单个元素的原因及修复方案

可能的原因及对应解决方法

1. 页面元素未完全加载

动态渲染的博彩网站通常需要一定时间加载所有赛事元素,直接执行查找可能只抓到已加载的第一个元素。用显式等待确保所有目标元素加载完成:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待最多10秒,直到所有class为event-row-container的元素出现
matches = WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located((By.CLASS_NAME, "event-row-container"))
)

for match in matches:
    print(match)

2. 目标元素位于iframe内

检查页面是否嵌套了iframe,若赛事元素在iframe中,必须先切换到对应iframe才能查找:

# 定位并切换到iframe(可根据实际情况用id、name等定位)
iframe = driver.find_element(By.TAG_NAME, "iframe")
driver.switch_to.frame(iframe)

# 执行元素查找
matches = driver.find_elements(By.CLASS_NAME, "event-row-container")

# 操作完成后切回主文档(如需操作其他区域元素)
driver.switch_to.default_content()

3. 页面需要滚动加载更多元素

部分网站会在滚动到页面底部时才加载后续赛事,先滚动再查找:

# 滚动到页面底部触发加载
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

# 等待新元素加载(可根据网络情况调整等待时间)
import time
time.sleep(2)

matches = driver.find_elements(By.CLASS_NAME, "event-row-container")

4. 改用CSS_SELECTOR定位

偶尔CLASS_NAME定位会有隐性兼容问题,换用CSS选择器尝试:

matches = driver.find_elements(By.CSS_SELECTOR, ".event-row-container")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:50:35