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

如何定位并点击类名相同的Combobox下拉选择框中的选项

Selenium定位下拉选择框元素失败问题

各位早上好,我在使用Selenium定位网页元素时遇到了问题,无法找到下拉选择框元素并点击它,不清楚问题出在哪里。

页面HTML截图:
页面HTML截图

我尝试了以下代码,还进行了网页抓取来验证元素是否正确,但返回值始终为0:

test1 = driver.find_elements(By.CLASS_NAME,'el-select-dropdown__wrap el-scrollbar__wrap')#DIV
test2 = driver.find_elements(By.CLASS_NAME,'el-scrollbar__view el-select-dropdown__list') #Ul class
op_unitaria = driver.find_element(By.CLASS_NAME,'el-select-dropdown__item') # 选项unitario
op_unitaria01 = driver.find_elements(By.CLASS_NAME,'el-select-dropdown__item') #包含所有选项的列表

valor = op_unitaria01[30].get_attribute("value")
print(valor)
valor1 = op_unitaria01[100].get_property("value")
print(valor1)
print(valor1.text)
time.sleep(5)

问题分析与解决思路

  1. CLASS_NAME定位的错误用法
    By.CLASS_NAME不支持同时传入多个用空格分隔的类名,你写的'el-select-dropdown__wrap el-scrollbar__wrap'会被当成一个完整的类名去匹配,自然找不到元素。如果要定位带多个类的元素,改用CSS_SELECTOR,写法为'.el-select-dropdown__wrap.el-scrollbar__wrap'(用点号连接多个类,无空格)。

  2. 下拉框的加载逻辑问题
    这类下拉框通常是点击触发按钮后才会渲染选项列表,你直接去查找选项,大概率元素还没加载出来。正确流程是:

    • 先定位并点击触发下拉的元素(比如带el-select类的输入框/按钮)
    • 用显式等待(WebDriverWait)等待选项列表出现,不要依赖time.sleep硬等
    • 再去定位并操作下拉选项
  3. 索引越界的风险
    直接取op_unitaria01[30]或[100],如果下拉选项总数不足,会直接抛出索引越界错误。建议先判断列表长度,再执行后续操作。

修正后的示例代码

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

# 1. 等待并点击触发下拉框展开
select_trigger = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, ".el-select"))
)
select_trigger.click()

# 2. 等待下拉选项列表完全加载
wait = WebDriverWait(driver, 10)
options_list = wait.until(
    EC.presence_of_all_elements_located((By.CLASS_NAME, "el-select-dropdown__item"))
)

# 3. 检查选项数量并执行操作
print(f"下拉选项总数:{len(options_list)}")
if len(options_list) > 30:
    target_option = options_list[30]
    print(target_option.get_attribute("value"))
    print(target_option.text)
    target_option.click()
else:
    print("选项数量不足30个")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:58:23