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

Python Selenium校验下拉选项时相同列表无法断言问题求助

Selenium下拉框选项校验问题修复

核心错误原因

  • 定位逻辑错误:你写的XPath定位的是<select>下拉框元素本身,而非下拉框下的<option>选项子元素。find_elements返回的列表仅包含1个select元素对象,调用该对象的text属性得到的是所有选项拼接的长文本,不是每个选项单独的文本集合。
  • 判断逻辑错误:
    1. 你判断excess in excess_list时,excess是存储文本的列表,excess_list是WebElement对象列表,两类完全不同的数据不可能存在包含关系,该判断永远为假。
    2. 之前遍历预期列表的临时变量excesses在循环结束后,仅会保留最后一个预期值US$10,000 per annum,你拿整个文本列表判断是否在这个字符串中,也永远不成立。
  • 流程错误:你在for循环内部直接写了return text,第一次循环执行完就会直接终止函数,根本不会遍历完所有元素。

修复后的实现方案

推荐使用Selenium官方提供的Select工具类处理下拉框,代码更简洁可靠:

# 首先导入Select类
from selenium.webdriver.support.ui import Select

def getListOfExcess(self):
    expected_excess = ["Nil excess", "US$250 per annum", "US$500 per annum", "US$800 per claim",
                      "US$1,000 per annum", "US$1,600 per claim", "US$2,500 per annum", "US$5,000 per annum",
                      "US$10,000 per annum"]
    # 定位select下拉框元素
    select_ele = self.driver.find_element_by_xpath("//div[@name='pExcess']/div[2]/div/div/div/select")
    # 实例化Select对象
    select = Select(select_ele)
    # 获取所有选项的文本,生成实际选项列表,加strip()去除首尾可能存在的空白字符
    actual_excess = [option.text.strip() for option in select.options]
    
    # 校验两个列表是否一致(如果不要求选项顺序,可先对两个列表排序后再比对)
    if actual_excess == expected_excess:
        print('Excess type for Bronze are correct')
        return True
    else:
        print('Excess type for Bronze are NOT correct')
        print(f"预期选项:{expected_excess}")
        print(f"实际选项:{actual_excess}")
        return False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:06:03