使用Selenium向日期输入框传值报错:ElementNotInteractableException如何解决?
解决Selenium中日期输入框ElementNotInteractableException问题
问题核心
点击"Neste"按钮进入后续页面后,向DatoEksporteringFraNorge输入框传入日期时触发ElementNotInteractableException,主要原因包括:
- 仅等待元素存在(
presence_of_element_located)不代表元素已处于可交互状态 - 页面切换后加载未完成,短时间等待不足以让元素就绪
- 该日期输入框可能是自定义控件,原生input存在隐藏或交互限制
方案1:等待元素可交互并确保页面就绪
将元素等待条件替换为element_to_be_clickable,并增加点击激活步骤,确保输入框处于可操作状态:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By if __name__ == '__main__': checkLink = "https://www.skatteetaten.no/person/avgifter/bil/eksportere/regn-ut/" options = Options() options.add_argument("start-maximized") options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 1}) options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('excludeSwitches', ['enable-logging']) options.add_experimental_option('useAutomationExtension', False) options.add_argument('--disable-blink-features=AutomationControlled') srv = Service() driver = webdriver.Chrome(service=srv, options=options) waitWD = WebDriverWait(driver, 15) driver.get(checkLink) # 切换目标iframe waitWD.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='iFrameResizer0']"))) # 输入车牌号(等待元素可点击) waitWD.until(EC.element_to_be_clickable((By.XPATH,'//input[@id="Regnummer"]'))).send_keys("VH77934") # 点击下一步按钮 waitWD.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Neste"]'))).click() # 等待日期输入框可交互并激活 date_input = waitWD.until(EC.element_to_be_clickable((By.XPATH,'//input[@id="DatoEksporteringFraNorge"]'))) date_input.click() date_input.send_keys("30.11.2023") driver.quit()
方案2:JavaScript直接设置值(针对自定义控件)
如果方案1无效,说明输入框是自定义日期控件,原生input被隐藏或无法直接交互,可通过JavaScript强制修改value属性:
替换日期输入部分的代码:
# 等待元素存在 date_input = waitWD.until(EC.presence_of_element_located((By.XPATH,'//input[@id="DatoEksporteringFraNorge"]'))) # 使用JavaScript直接设置输入框值 driver.execute_script("arguments[0].value = '30.11.2023';", date_input)
额外注意事项
- 避免过度依赖
time.sleep(),优先使用WebDriverWait显式等待,它会在元素满足条件时立即执行,稳定性更高 - 点击"Neste"后页面可能存在DOM更新,需确保等待时长足够覆盖加载过程
- 若后续页面切换了iframe,需重新切换到对应iframe(本案例中点击下一步后仍在原iframe内)
内容的提问来源于stack exchange,提问作者Rapid1898
相关产品推荐
相关产品推荐

