使用Selenium Python处理非选择式下拉列表:打印选项并选曼哈顿
问题分析与解决方案
你的代码无效的核心原因是:页面上的“city”下拉框不是原生HTML <select> 元素,而是基于输入框实现的自定义下拉组件(这类组件常见于Vue/React等前端框架),Selenium的Select类仅能处理原生<select>标签,因此无法识别和操作该下拉选项。
以下是针对需求的修正代码,包含两个功能:打印所有城市选项、输入部分文本后选择对应选项。
完整代码示例
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time PATH = "/usr/local/bin/chromedriver" driver = webdriver.Chrome(PATH) driver.get("https://upxland.me/properties/") try: # 1. 定位城市输入框,等待可点击并点击展开下拉列表 city_input = WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.ID, 'input-74')) ) city_input.click() time.sleep(0.5) # 短暂等待下拉列表展开 # 2. 等待所有下拉选项加载完成,定位所有选项元素 city_options = WebDriverWait(driver, 20).until( EC.visibility_of_all_elements_located((By.XPATH, "//div[@role='listbox']//div[@role='option']")) ) # 打印所有城市选项 print(f"总共有 {len(city_options)} 个城市选项:") for option in city_options: print(option.text.strip()) # 3. 输入部分文本(如"Manha"),过滤选项并选择"Manhattan" city_input.clear() city_input.send_keys("Manha") time.sleep(0.5) # 等待选项过滤完成 # 重新定位过滤后的选项,找到匹配的Manhattan filtered_options = WebDriverWait(driver, 20).until( EC.visibility_of_all_elements_located((By.XPATH, "//div[@role='listbox']//div[@role='option']")) ) for option in filtered_options: if option.text.strip() == "Manhattan": option.click() break time.sleep(3) # 停留查看效果 except Exception as e: print(f"出错信息:{str(e)}") finally: driver.quit()
关键说明
- 元素定位调整:自定义下拉组件的选项通常会带有
role='option'属性,父容器为role='listbox',用XPath可以精准定位这些元素。 - 交互逻辑修正:需要先点击输入框展开下拉列表,才能获取到所有选项;输入部分文本后,下拉列表会自动过滤,此时重新定位选项并选择目标值。
- 等待机制:使用
element_to_be_clickable确保输入框可交互,visibility_of_all_elements_located确保选项完全加载可见,避免因元素未加载导致的报错。
内容的提问来源于stack exchange,提问作者Chloe
相关产品推荐
相关产品推荐

