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
相关产品推荐
相关产品推荐

