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

使用Selenium Python向Web输入框输入数字时格式异常的技术求助

问题解决指导

问题原因

你的输入框通过onkeypress事件绑定了autoMask函数,按###-######-#规则格式化输入。手动输入时每个字符都会触发一次按键事件,格式化逻辑能逐步处理;但Selenium的send_keys一次性传入整个字符串时,事件触发机制和手动输入不同,导致格式化逻辑处理异常。

解决方案

1. 模拟逐个字符输入

循环遍历字符串的每个字符,逐个调用send_keys,确保每个字符输入时都触发onkeypress事件,让格式化逻辑正常工作:

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

national_id = "1985225000"
input_element = WebDriverWait(driver, 50).until(
    EC.element_to_be_clickable((By.XPATH, "//input[@name='search.popup.customer.customerCertificationNumber'][@type='text']"))
)
# 先清空输入框(可选,防止已有内容干扰)
input_element.clear()
for char in national_id:
    input_element.send_keys(char)
    time.sleep(0.1)  # 短延迟确保事件被处理

2. 直接修改DOM属性并触发事件

绕过按键事件,直接设置输入框的value属性,再触发input或change事件让页面识别值的变化:

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

national_id = "1985225000"
input_element = WebDriverWait(driver, 50).until(
    EC.presence_of_element_located((By.XPATH, "//input[@name='search.popup.customer.customerCertificationNumber'][@type='text']"))
)
# 直接设置value
driver.execute_script("arguments[0].value = arguments[1];", input_element, national_id)
# 触发input事件,确保页面检测到值更新
driver.execute_script("arguments[0].dispatchEvent(new Event('input'));", input_element)
# 可选:触发change事件,适配某些依赖该事件的逻辑
driver.execute_script("arguments[0].dispatchEvent(new Event('change'));", input_element)

3. 激活输入框后再操作

如果上述方法仍有问题,先点击输入框确保其处于激活状态,再执行输入操作:

input_element = WebDriverWait(driver, 50).until(
    EC.element_to_be_clickable((By.XPATH, "//input[@name='search.popup.customer.customerCertificationNumber'][@type='text']"))
)
input_element.click()  # 激活输入框
# 之后执行逐个字符输入或直接修改属性的操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:52:37