Selenium Java报错ElementNotInteractableException:无法选择下拉菜单选项
问题:无法选择下拉菜单中的“Code 128 (standard)”选项
尝试通过Selenium操作下拉菜单选择“Code 128 (standard)”时始终失败,抛出ElementNotInteractableException异常,提示元素不可交互。
所用代码
WebDriver driver = Driver.get(); driver.manage().window().setPosition(new Point(-1000, 0)); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://www.barcode-generator.org/"); BrowserUtils.waitFor(2); driver.findElement(By.className("iubenda-cs-close-btn")).click(); BrowserUtils.waitFor(2); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement selectElement = driver.findElement(By.xpath("//select[@id='code_selector']")); Select select = new Select(selectElement); List<WebElement> options = select.getOptions(); BrowserUtils.waitFor(4); System.out.println("options.size() = " + options.size()); select.selectByVisibleText("Code 128 (standard)"); driver.findElement(By.id("barcode_data")).sendKeys("abc");
报错信息
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Starting ChromeDriver 114.0.5735.90 (386bc09e8f4f2e025eddae123f36f6263096ae49-refs/branch-heads/5735@{#1052}) on port 53482 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. Haz 18, 2023 1:53:26 ÖS org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: W3C options.size() = 67 org.openqa.selenium.ElementNotInteractableException: element not interactable: Element is not currently visible and may not be manipulated (Session info: chrome=114.0.5735.134) Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
解决方案
该网站的下拉菜单并非原生<select>元素,而是用HTML/CSS模拟的自定义下拉组件,原生的code_selector元素处于隐藏状态,直接操作它必然触发不可交互异常。可改用以下方式操作:
- 先点击触发下拉展开的按钮(页面上的自定义下拉容器)
- 等待选项列表加载完成后,定位目标选项并点击
修改后的示例代码:
WebDriver driver = Driver.get(); driver.manage().window().maximize(); // 用显式等待替代硬等待,提升稳定性 WebDriverWait wait = new WebDriverWait(driver, 10); driver.get("https://www.barcode-generator.org/"); // 关闭隐私弹窗 wait.until(ExpectedConditions.elementToBeClickable(By.className("iubenda-cs-close-btn"))).click(); // 点击自定义下拉容器,展开选项列表 WebElement dropdownTrigger = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.select-box"))); dropdownTrigger.click(); // 定位并点击目标选项 WebElement targetOption = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(), 'Code 128 (standard)')]"))); targetOption.click(); // 输入条码数据 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("barcode_data"))).sendKeys("abc");
另外,建议替换所有BrowserUtils.waitFor()的硬等待为显式等待,避免因页面加载延迟导致的元素定位失败问题。
内容的提问来源于stack exchange,提问作者ihsan akcair
相关产品推荐
相关产品推荐

