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

使用Java开发Selenium入门程序时遇ElementNotInteractableException错误

解决Selenium中ElementNotInteractableException问题(谷歌搜索场景)

在用Java开发Selenium脚本时,编写了打开谷歌并执行基础搜索的代码,但点击搜索按钮时抛出错误:
org.openqa.selenium.ElementNotInteractableException: element not interactable

经排查,搜索按钮的类名gNO89b被应用在两个按钮上,程序定位到了搜索建议下拉框中的按钮,而非主界面的搜索按钮。尝试过添加等待、模拟ESC关闭下拉框等方法,均未解决问题。

用户原代码

public static void SeleniumTest() {
    WebDriver Chrome = new ChromeDriver();
    Chrome.get("https://www.google.co.uk");

    WebElement AcceptCookies = Chrome.findElement(By.id("L2AGLb"));//find cookie prompt and accept button
    AcceptCookies.click();

    WebElement SearchBox = Chrome.findElement(By.className("gLFyf")); //find search field
    SearchBox.click();
    SearchBox.sendKeys("Selenium");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        System.out.print("thread sleep failed with error " + e);
    }

    WebElement SearchButton = Chrome.findElement(By.className("gNO89b")); //find the search button
    SearchButton.click(); // and click it - error occurs here
}

无效尝试代码

显式等待(未生效)

WebDriverWait wait = new WebDriverWait(Chrome, java.time.Duration.ofSeconds(10));
WebElement newButton = wait.until(news -> news.findElement(By.className("gNO89b")));
newButton.click();

模拟ESC关闭下拉框(未生效)

Actions action = new Actions(Chrome);
action.keyDown(Keys.ESCAPE).sendKeys().perform(); //remove?

可行解决方案

1. 使用精准定位表达式

放弃单一类名定位,改用更独特的XPath或CSS选择器,直接定位主界面的搜索按钮:

  • 按按钮的value属性定位:
WebElement searchButton = Chrome.findElement(By.xpath("//input[@class='gNO89b' and @value='Google Search']"));
  • 按父容器定位(主界面按钮在特定div下):
WebElement searchButton = Chrome.findElement(By.xpath("//div[@class='FPdoLc lJ9FBc']//input[@class='gNO89b']"));

2. 优化显式等待条件

之前的等待仅确认元素存在,但未确保元素可交互,改用elementToBeClickable条件:

WebDriverWait wait = new WebDriverWait(Chrome, Duration.ofSeconds(10));
WebElement searchButton = wait.until(ExpectedConditions.elementToBeClickable(
    By.xpath("//input[@class='gNO89b' and @value='Google Search']")
));
searchButton.click();

3. 替代方案:直接回车提交搜索

无需定位按钮,在搜索框输入内容后直接模拟回车键提交:

SearchBox.sendKeys("Selenium");
SearchBox.sendKeys(Keys.ENTER);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:15:08