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

Python Selenium爬虫始终返回空列表问题求助

解决Selenium查找指定Class元素返回空列表的问题

核心原因及修复方案

1. 页面动态渲染未完成就执行查找

目标网站内容是动态加载的,直接调用find_elements时,project-info__elem元素还未渲染生成,导致返回空列表。需添加显式等待,等待元素加载完成后再执行查找。

修改后的完整代码:

from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.chrome.service import Service as ChromeService 
from webdriver_manager.chrome import ChromeDriverManager 
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions() 
options.headless = True 

driver = webdriver.Chrome(service=ChromeService( 
    ChromeDriverManager().install()), options=options) 

url = 'https://maclear.ch/en/projects' 
driver.get(url) 

# 最长等待10秒,直到目标元素出现
wait = WebDriverWait(driver, 10)
elements = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'project-info__elem')))

# 输出结果
print(f"找到元素数量:{len(elements)}")
for elem in elements:
    print(elem.text)

2. 无头模式窗口尺寸过小导致元素未渲染

无头模式默认窗口尺寸极小,部分响应式网站会隐藏或不渲染非可视区域的元素。需设置合理的窗口尺寸:

在options.headless = True后添加以下代码:

# 设置无头浏览器窗口尺寸为1920*1080
options.add_argument("--window-size=1920,1080")

3. 验证元素是否嵌套在iframe中(排查项)

如果上述方案无效,检查目标元素是否位于iframe内部。若是,需先切换到iframe再执行查找:

# 根据实际页面的iframe标识修改(示例用ID定位)
iframe = driver.find_element(By.ID, "target-iframe-id")
driver.switch_to.frame(iframe)

# 切换后再查找元素
elements = driver.find_elements(By.CLASS_NAME, 'project-info__elem')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:35:12