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

使用Selenium+Python无法修改Angular日期输入框文本/值的问题求解

问题根因

该日期输入框为前端受控组件,直接修改value属性或调用send_keys没有触发元素绑定的input/change事件,前端框架内部存储的状态未同步更新,提交请求时依然会读取原有状态值。


解决方案

方案1:模拟真实用户操作路径

先激活聚焦输入框,清空原有内容后再输入目标值:

from selenium.webdriver.common.keys import Keys

date_field = driver.find_element_by_id('dataInicio')
# 点击聚焦元素
date_field.click()
# 全选原有内容后删除
date_field.send_keys(Keys.CONTROL, 'a')
date_field.send_keys(Keys.BACKSPACE)
# 输入目标日期
date_field.send_keys(date_value)

方案2:修改值后主动触发事件

JS修改value属性后手动触发事件,同步前端状态:

nvg.execute_script("""
arguments[0].value = arguments[1];
// 触发输入事件通知前端值变更
arguments[0].dispatchEvent(new Event('input', { bubbles: true }));
// 触发变更事件确保状态同步完成
arguments[0].dispatchEvent(new Event('change', { bubbles: true }));
""", end_date_field, end_month_date)

方案3:React受控组件特殊适配

如果页面使用React框架开发,默认修改value的方式无法覆盖受控组件的状态绑定,需调用原生属性赋值方法处理:

nvg.execute_script("""
const inputEl = arguments[0];
const targetValue = arguments[1];
// 获取原生value赋值方法
const nativeValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
nativeValueSetter.call(inputEl, targetValue);
// 触发输入事件同步状态
inputEl.dispatchEvent(new Event('input', { bubbles: true }));
""", end_date_field, end_month_date)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:15:08