You need to enable JavaScript to run this app. Python Selenium如何读取多选下拉框中已激活的选中选项
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium如何读取多选下拉框中已激活的选中选项

Selenium读取自定义多选下拉框已激活选项解决方案

原代码错误原因

  • 适配对象错误:Selenium内置Select工具类仅支持原生<select>标签,你传入的XPath指向的是自定义多选组件的<ul>容器,完全不符合Select类的入参要求,必然执行失败。
  • 语法错误:Select类获取已选选项的属性名为all_selected_options(复数),原代码写为单数all_selected_option,即使传入正确的<select>元素也会报属性不存在错误。
  • 取值逻辑错误:all_selected_options返回的是已选元素列表,原代码直接调用get_attribute会报错,需要遍历列表逐个取值。

可行实现方案

方案1:调用原生隐藏<select>标签读取(推荐)

你的代码里原生<select>虽然设置了display: none隐藏,但已选<option>上自带selected属性标记状态,直接定位该元素用Select类读取即可,不需要操作前端可见的自定义下拉组件:

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

def get_selected_values_from_dropdown(self):
    try:
        # 直接定位原生select标签,不需要传ul的xpath
        select_ele = WebDriverWait(self.driver, 20).until(
            EC.presence_of_element_located((By.ID, "WidgetStatus_DD"))
        )
        select = Select(select_ele)
        # 遍历所有已选选项取value
        return [option.get_attribute("value") for option in select.all_selected_options]
    except NoSuchElementException as e:
        print(f"Dropdown element not found: {str(e)}")
        return []

# 调用部分
record = dict()
if key == "widgets":
    widgets = self.get_selected_values_from_dropdown()
    record[key] = ", ".join(widgets)

方案2:直接读取自定义下拉的激活类选项

如果需要和前端可见的自定义下拉状态对齐,直接定位<ul>下带active类的<li>元素取值即可,不需要用Select类:

def get_selected_values_from_dropdown(self, ul_xpath):
    try:
        # 等待ul容器加载完成
        ul_ele = WebDriverWait(self.driver, 20).until(
            EC.presence_of_element_located((By.XPATH, ul_xpath))
        )
        # 定位所有带active类的li下的input元素
        active_items = ul_ele.find_elements(By.XPATH, './li[contains(@class, "active")]//input')
        # 遍历取value
        return [item.get_attribute("value") for item in active_items]
    except NoSuchElementException as e:
        print(f"Dropdown element at {ul_xpath} not found: {str(e)}")
        return []

# 调用部分
xpath = '//*[@id="addActivityTable"]/tbody/tr[17]/td[2]/div/ul'
record = dict()
if key == "widgets":
    widgets = self.get_selected_values_from_dropdown(xpath)
    record[key] = ", ".join(widgets)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:15:03