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

搜索文章功能自动化测试异常:搜索框无法交互问题排查

搜索功能自动化测试问题排查

问题背景

对站点https://www.buletintv3.my/的搜索文章功能做自动化测试时,点击搜索SVG图标后搜索框未弹出,执行测试代码时报错:

元素应可交互 {By.xpath: //input[@class='form-control me-sm-2']} 元素: '' 实际状态: hidden, opacity=1

测试代码如下:

@Test
public void testSearchArticles() {
    extentTest = extentManager.getExtentReports().createTest("Search Articles Test");

    $x("//*[@id=\"__next\"]/div[3]/section[1]/div/nav/div[1]/button").click();
    $x("//input[@class='form-control me-sm-2']").click();
    $x("//input[@class='form-control me-sm-2']").setValue("bola");
    $x("//input[@class='form-control me-sm-2']").pressEnter();
}

问题分析

报错提示输入框处于hidden状态,核心原因是操作输入框的时机过早——点击搜索按钮后页面还没完成搜索框的显示渲染,就直接执行输入操作;另外代码里的元素定位也存在稳定性问题。

代码与测试思路的问题点

  1. 硬编码XPath脆弱:搜索按钮的XPath完全依赖页面层级结构,页面布局稍有变动就会定位失败,且无法直观体现元素的功能属性。
  2. 无等待机制:点击搜索按钮后,没有等待搜索框完成显示/渲染流程,直接操作不可见元素,触发hidden状态报错。
  3. 重复定位冗余:多次重复编写相同的输入框XPath,既冗余又容易出错,也没有先验证元素可见性再执行操作。

修复方案

1. 替换为稳定的元素定位

  • 搜索按钮:放弃依赖层级的XPath,改用功能相关属性定位(示例需根据实际页面结构微调):
    // 定位包含搜索图标的按钮
    WebElement searchBtn = driver.findElement(By.xpath("//button[.//svg[contains(@aria-label, 'search')]]"));
    
  • 搜索输入框:结合父容器标识+class定位,提升稳定性:
    By searchInputLoc = By.xpath("//div[contains(@class, 'search-bar')]/input[@class='form-control me-sm-2']");
    

2. 添加显式等待机制

点击搜索按钮后,显式等待输入框变为可见且可交互,避免操作时机过早:

@Test
public void testSearchArticles() {
    extentTest = extentManager.getExtentReports().createTest("Search Articles Test");

    // 定位并点击搜索按钮
    WebElement searchBtn = driver.findElement(By.xpath("//button[.//svg[contains(@aria-label, 'search')]]"));
    searchBtn.click();

    // 显式等待搜索输入框可见且可交互
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    WebElement searchInput = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='form-control me-sm-2']")));

    // 执行搜索操作
    searchInput.sendKeys("bola");
    searchInput.sendKeys(Keys.ENTER);
}

3. 额外优化点

  • 验证搜索按钮点击有效性:点击后可检查搜索框容器的可见性,确认触发了搜索框的显示逻辑。
  • 若常规点击失效(比如元素被遮挡),尝试用JS执行点击:
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].click();", searchBtn);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:20:41