升级Selenium与Firefox后遭遇ElementNotInteractableException问题求助
我之前在Firefox 57+Geckodriver 0.19的组合下碰到过一模一样的ElementNotInteractableException问题,结合你的报错信息和必须使用Firefox配置文件的业务需求,给你整理几个靠谱的解决方案:
首先看你报错里的Capabilities参数,有个关键线索:
moz:webdriverClick=false
这是Firefox新版本里的默认设置问题,再加上Selenium3.4.0和Geckodriver的兼容性限制,导致元素明明被找到却无法触发点击。
1. 调整Firefox配置文件,启用原生WebDriver点击
在初始化FirefoxDriver前,给你的FirefoxProfile添加以下配置,强制开启WebDriver的原生点击行为:
FirefoxProfile profile = new FirefoxProfile(); // 启用WebDriver原生点击逻辑 profile.setPreference("webdriver.click", true); // 确保dom.webdriver.enabled处于开启状态 profile.setPreference("dom.webdriver.enabled", true); // 禁用页面加载时的弹窗屏蔽(避免弹窗遮挡目标元素) profile.setPreference("dom.disable_open_during_load", false); FirefoxOptions options = new FirefoxOptions(); options.setProfile(profile); WebDriver driver = new FirefoxDriver(options);
2. 优化元素等待逻辑,确保元素完全可交互
你当前的FluentWait只等待元素存在,但有时候元素虽然DOM已加载,却还处于不可点击的状态(比如还在渲染、被覆盖)。可以修改等待条件,明确等待元素可点击:
public void clickOnUsers(){ WebElement users = new FluentWait<>(driver) .withTimeout(10, TimeUnit.SECONDS) .pollingEvery(500, TimeUnit.MILLISECONDS) .ignoring(NoSuchElementException.class) .ignoring(ElementNotInteractableException.class) .until(ExpectedConditions.elementToBeClickable(By.linkText("Users"))); users.click(); }
如果坚持用你原来的FluentWebElement语法,也可以调整等待条件为elementToBeClickable,而不是默认的元素存在。
3. 备选方案:用JavaScriptExecutor强制触发点击
如果上面的方法还是不行,大概率是目标元素被页面其他元素(比如固定导航栏、加载动画)遮挡了。这时候可以用JS直接在DOM层面触发点击事件,绕过Selenium的交互检查:
public void clickOnUsers(){ FluentWebElement users = within(secs(10)).link(By.linkText("Users")); ((JavascriptExecutor) driver).executeScript("arguments[0].click();", users.getElement()); }
4. 版本兼容性优化
你的Selenium3.4.0版本相对较旧,对Geckodriver的支持不够完善。建议尝试把Selenium升级到3.8.1及以上版本(这个版本对Geckodriver 0.19/0.20的兼容性更好),同时确保Geckodriver和Firefox的版本匹配:
- Geckodriver 0.19.0 → Firefox 55-57
- Geckodriver 0.20.0 → Firefox 56-59
升级Selenium时记得同步调整项目依赖。
另外,别忘了检查页面是否有未完成的AJAX请求,必要时可以增加等待页面加载完成的逻辑,避免在页面未就绪时触发点击。
内容的提问来源于stack exchange,提问作者N.Hol

