尝试使用 Java 制作一个简单的 selenium 入门应用程序,但在搜索按钮上不断收到元素不可交互的错误

问题描述 投票:0回答:1

所以,我正在尝试用Java学习Selenium,制作一个简单的方法来打开谷歌,并进行基本搜索。但是,我收到错误

org.openqa.selenium.ElementNotInteractableException: element not interactable

以下是完整代码供参考:

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
}

据我所知,搜索按钮类名称似乎应用于两个不同的按钮,当我想在默认用户界面。

我尝试过添加等待、移动光标并关闭建议框,但当唯一可见的搜索框是主页上的搜索框时,我仍然最终收到错误。

我是否需要对特定元素进行更清晰的查找,或者我是否缺少 Selenium 的其他一些特性以使其正确找到预期的按钮?

我尝试添加 waituntil 以确保按钮可见,但这没有用。

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

我还尝试关闭上下文菜单以确保唯一的按钮是主 UI 中的按钮,但这也无法按预期工作。

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

java selenium-webdriver selenium-chromedriver webdriver
1个回答
0
投票

所以问题正如您所怀疑的......有两个元素与定位器(“gNO89b”的类名)匹配。找到的第一个元素不可交互,因为脚本运行得太快,搜索结果面板尚未打开,第一个元素完全可见且可交互。您可以通过几种方式解决这个问题。

方法#1
使用适当的等待

String url = "https://www.google.co.uk";

driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.className("gLFyf"))).sendKeys("Selenium");
wait.until(ExpectedConditions.elementToBeClickable(By.className("gNO89b"))).click();

方法#2
发送带有搜索词的回车

String url = "https://www.google.co.uk";

driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.className("gLFyf"))).sendKeys("Selenium\n");

提示#1
无论您选择哪种方式,每次通话时使用

WebDriverWait
始终是最佳实践。即使没有必要,它也不会减慢您的代码速度,但会有助于防止间歇性故障(如果网站今天运行速度有点慢等)。

提示#2
始终在开发控制台中测试您的定位器。使用

$$()
作为 CSS 选择器,使用
$x()
作为 XPath。这将极大地帮助您在实际运行任何代码之前找到独特的定位器并识别问题。例如,
$$(".gNO89b")
代表 CSS 选择器语法中的搜索按钮。这将返回 2 个元素。如果展开搜索结果,您可以将鼠标悬停在返回的每个元素上,并看到它在页面上突出显示。然后您可以看到返回的第二个元素就是您想要的元素...从而在运行脚本之前确定问题。

© www.soinside.com 2019 - 2024. All rights reserved.