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

如何用Selenium Java定位测试div构建的自动补全动态下拉框

解决Selenium Java操作div动态自动补全下拉框的问题

针对flydubai网站(https://www.flydubai.com/en-gb/)的div自动补全下拉框测试问题,你遇到的核心痛点是手动检查元素时下拉框失焦消失,以及现有代码定位元素不够稳定导致无法遍历选项。以下是针对性的解决方案:

问题分析

你现有代码存在几个潜在问题:

  • 依赖动态生成的class(如jss1、css-1l0ew3p)定位元素,这类class会随页面渲染变化,容易失效
  • 下拉选项的定位范围太宽泛,可能匹配到页面其他无关元素
  • 触发下拉框的逻辑不够稳定,未确保输入框完全就绪

解决方案步骤

1. 优化元素定位(避免动态class)

优先使用文本、placeholder、固定属性或父容器层级定位,替代易变的动态class:

  • 单向选项(one-way):通过文本“One way”结合父容器定位
  • 出发地输入框:通过固定ID或placeholder定位

2. 稳定触发下拉框并等待加载

  • 先清除输入框原有内容,再输入关键词确保触发下拉建议
  • 先等待下拉框的容器(role="listbox")出现,再定位内部选项,确保建议完全加载

3. 精准遍历下拉选项

定位到目标autocomplete的listbox容器后,再遍历内部的role="option"元素,避免误匹配

修正后的完整代码

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import java.util.List;

// 假设d是已初始化的WebDriver实例

// 1. 处理Cookie弹窗(优化定位,避免依赖动态class)
WebDriverWait wait = new WebDriverWait(d, 15);
WebElement acceptCookies = wait.until(ExpectedConditions.elementToBeClickable(
        By.xpath("//button[text()='Accept all']")
));
acceptCookies.click();

// 2. 选择单向航班(用文本定位,替代动态class)
WebElement oneWayOption = wait.until(ExpectedConditions.elementToBeClickable(
        By.xpath("//span[text()='One way']/ancestor::div[@role='radio']")
));
oneWayOption.click();

// 3. 触发出发地下拉框并输入关键词
WebElement fromInput = wait.until(ExpectedConditions.elementToBeClickable(
        By.id("from-airportsList")
));
fromInput.clear(); // 清除原有内容
fromInput.sendKeys("Gla"); // 输入关键词触发建议

// 4. 等待下拉建议容器出现,再获取所有选项
WebElement suggestionsContainer = wait.until(ExpectedConditions.visibilityOfElementLocated(
        By.xpath("//div[@id='from-airportsList']/following-sibling::div//div[@role='listbox']")
));
List<WebElement> suggestions = suggestionsContainer.findElements(By.xpath(".//div[@role='option']"));

// 5. 遍历选项并选择目标
boolean suggestionFound = false;
for (WebElement suggestion : suggestions) {
    String text = suggestion.getText().trim();
    System.out.println("检测到建议:" + text);
    if (text.contains("Glasgow")) {
        suggestion.click();
        suggestionFound = true;
        break;
    }
}

// 断言验证
Assert.assertTrue(suggestionFound, "未找到包含Glasgow的下拉建议");

解决“检查元素时下拉框消失”的技巧

手动调试时,按以下步骤操作可以冻结下拉框:

  1. 点击输入框触发下拉建议出现
  2. 立刻按F8(Chrome DevTools暂停脚本执行),此时页面脚本暂停,下拉框不会因失焦消失
  3. 正常打开元素检查器即可查看下拉框的DOM结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:05:22