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

如何在Selenium Python中处理非Select类下拉菜单

Selenium Python 处理非Select类型下拉菜单(选中Completed选项)

场景说明

在Selenium Python环境下,需要处理非原生Select标签的下拉菜单,目标是选中并点击菜单中的“Completed”选项。

对应HTML结构

<span class="ant-select-selection-item" title="Completed">Completed</span>

原尝试代码

try :
    element = WebDriverWait(driver,5).until(ec.presence_of_element_located((By.XPATH,'/html/body/div[4]/div/div[2]/div/div/div[2]/div/div[2]/div[3]/div/p/div/div/span[1]/input')))   
    element.click()                                                                           
    wait = WebDriverWait(driver, 10)
    option = wait.until(ec.presence_of_element_located((By.XPATH,'//span[@class="ant-select-selection-item" and @title="Completed"]')))
    option.click()
except:
    driver.quit()

优化方案及代码

原代码存在绝对XPATH稳定性差、等待条件仅检查元素存在而非可交互、选项定位可能指向已选中文本而非下拉选项等问题,以下是优化后的实现:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By

try:
    # 等待下拉触发框并点击展开选项(用相对定位替代绝对路径)
    dropdown_trigger = WebDriverWait(driver, 10).until(
        ec.element_to_be_clickable((By.XPATH, '//input[ancestor::div[contains(@class, "ant-select")]]'))
    )
    dropdown_trigger.click()
    
    # 等待Completed选项加载完成并可点击(针对Ant Design下拉选项的常见定位)
    completed_option = WebDriverWait(driver, 10).until(
        ec.element_to_be_clickable((By.XPATH, '//div[@class="ant-select-item-option-content" and text()="Completed"]'))
    )
    completed_option.click()
except Exception as e:
    print(f"操作失败:{str(e)}")
    driver.quit()

关键优化点

  • 避免绝对XPATH:绝对路径会因页面结构微小变化失效,改用相对定位(如通过父元素class关联)更稳定
  • 等待条件优化:使用element_to_be_clickable确保元素已加载完成且处于可交互状态,比presence_of_element_located更可靠
  • 选项定位修正:Ant Design下拉展开后的选项通常使用ant-select-item-option-content类,需根据实际页面的DOM结构调整定位规则
  • 异常处理增强:添加错误信息打印,便于排查问题,避免无提示退出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:23:12