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

Selenium执行send_keys填充输入框后内容消失,该如何排查解决?

问题原因

你操作的Origen和Destino字段属于Ant Design的Select下拉选择组件,并非普通文本输入框。该组件的交互逻辑是:仅输入内容但未选中下拉列表的匹配选项时,失焦后会自动清空未确认的输入内容,这就是你输入内容消失的核心原因。

解决方法

方案1:输入后选中对应下拉选项

输入关键词后等待下拉列表加载,点击匹配的选项完成选择,修改后的代码如下:

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


# 导航配置
options = webdriver.ChromeOptions()
options.add_argument('--start-maximized')
options.add_argument('--disable-extensions')

# Selenium 4.6+无需手动指定chromedriver路径,Driver Manager会自动适配
# driver_path = "C:/Users/Diego/Downloads/chromedriver.exe"
# chrome_options参数已弃用,改用options
driver = webdriver.Chrome(options = options)
 

# 双屏配置可按需开启
#driver.set_window_position(2000,0)
driver.maximize_window()
time.sleep(1)

# 打开目标页面
driver.get('https://www.starken.cl/cotizador')

# 填写Origen
origen_input = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input#rc_select_6")))
origen_input.send_keys('SANTIAGO')
# 等待下拉选项加载并点击匹配项
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH,"//div[contains(@class,'ant-select-item-option-content') and text()='SANTIAGO']"))).click()

# 填写Destino
destino_input = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input#rc_select_7")))
destino_input.send_keys('VINA DEL MAR')
# 等待下拉选项加载并点击匹配项
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH,"//div[contains(@class,'ant-select-item-option-content') and text()='VINA DEL MAR']"))).click()

方案2:输入后按回车快速选择

如果输入的关键词可以唯一匹配到第一个下拉选项,也可以直接加回车操作完成选择,无需额外定位选项元素:
首先导入Keys模块:

from selenium.webdriver.common.keys import Keys

然后修改输入逻辑:

WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input#rc_select_6"))).send_keys('SANTIAGO', Keys.ENTER)
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input#rc_select_7"))).send_keys('VINA DEL MAR', Keys.ENTER)
注意事项
  • 注意输入的文本要和下拉选项的文本完全匹配,包括大小写、特殊符号,匹配不到时可以将xpath中的text()='xxx'改为contains(text(),'xxx')做模糊匹配
  • 如果页面加载速度慢,可以适当延长WebDriverWait的超时时间,比如从5秒改为10秒避免超时报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:57:03