You need to enable JavaScript to run this app. Selenium Java中两个动态下拉框每次仅一个可正常运行问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Selenium Java中两个动态下拉框每次仅一个可正常运行问题排查

问题原因
  • 焦点抢占问题:出发城市选择完成后,输入焦点未自动切换到目的地输入框,部分场景下前一个输入框的联想层未完全关闭,会拦截后续的输入操作,导致目的地的输入和选择指令实际作用到了出发城市的输入框上
  • 元素激活逻辑缺失:MakeMyTrip的城市选择组件默认未激活,必须先点击触发编辑状态后才能正常输入关键词触发联想,现有代码仅对输入框执行sendKeys操作,未主动触发激活,会出现第二个输入框输入无效的问题
  • 硬等待不稳定:使用Thread.sleep做等待无法适配不同网络环境下的联想列表加载速度,经常出现联想列表还未渲染完成就执行了箭头选择+回车的操作,导致选择失效
解决方案

按以下逻辑调整代码:

  1. 每个城市选择操作前先点击对应输入框,主动触发组件激活,同时切换输入焦点
  2. 替换硬等待为显式等待,监听联想列表的渲染状态,确保操作生效
  3. 输入关键词后等待联想选项加载完成,再执行选择操作

修正后可运行代码:

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class CitySelectTest {
    public static void main(String[] args) {
        // 注意Windows路径反斜杠需要转义
        System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\Chrome Driver\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.makemytrip.com/");
        // 全局显式等待,适配网络波动
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        // 选择出发城市
        WebElement source = driver.findElement(By.id("fromCity"));
        source.click(); // 主动点击激活输入框
        WebElement fromInput = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@placeholder='From']")));
        fromInput.sendKeys("mum");
        // 等待联想列表加载完成再操作
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul[@role='listbox']")));
        fromInput.sendKeys(Keys.ARROW_DOWN);
        fromInput.sendKeys(Keys.ENTER);

        // 选择目的地城市
        WebElement destination = driver.findElement(By.id("toCity"));
        destination.click(); // 主动点击激活输入框,同时切换焦点
        WebElement toInput = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@placeholder='To']")));
        toInput.sendKeys("Pak");
        // 等待联想列表加载完成再操作
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul[@role='listbox']")));
        toInput.sendKeys(Keys.ARROW_DOWN);
        toInput.sendKeys(Keys.ENTER);
    }
}

如果使用Selenium 3及以下版本,将new WebDriverWait(driver, Duration.ofSeconds(10))修改为new WebDriverWait(driver, 10)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 03:06:04