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

Python Selenium:如何选择无唯一标识的下拉菜单指定选项

解决Select2下拉菜单无法定位选择的问题

针对你遇到的Select2下拉菜单无唯一UL类名导致无法选择“Property Owner Statement”的问题,这里提供可行的解决方案:

原代码存在几个核心问题:

  • 未初始化Select对象就直接调用方法
  • 这类自定义下拉(Select2)不属于原生HTML <select> 元素,不能直接用Selenium的Select类操作
  • 未等待下拉菜单展开就尝试定位选项

修正后的代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# 初始化浏览器
chrome_options = Options()
# 可按需添加无头模式等配置,比如:chrome_options.add_argument("--headless=new")
service = Service("你的ChromeDriver文件路径")
driver = webdriver.Chrome(service=service, options=chrome_options)

url = 'https://system.arthuronline.co.uk/genieliew1/dashboards/index'
driver.get(url)
wait = WebDriverWait(driver, 20)

# 1. 定位并点击触发Select2下拉的元素(通常是带select2-container类的输入框/触发按钮)
# 若页面有多个Select2,可结合其他特征细化定位,比如父元素ID
trigger_element = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "select2-container")))
trigger_element.click()

# 2. 等待下拉选项加载完成,用文本匹配定位目标选项
# 若选项是li元素,可把XPath改为//li[contains(text(), 'Property Owner Statement')]
target_option = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[contains(text(), 'Property Owner Statement')]")))
target_option.click()

# 操作完成后可关闭浏览器:driver.quit()

关键说明:

  • Select2是基于div/ul模拟的下拉组件,必须先触发菜单展开,再定位选项点击
  • 使用文本包含的XPath定位目标选项,摆脱对无唯一标识类名的依赖,适配性更强
  • 全程用WebDriverWait等待元素可交互,避免页面加载延迟导致的元素未找到问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:10:30