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

Java Selenium如何校验点击元素后src属性变化并通过if语句验证

问题原因&解决实现

核心错误点

  • Java字符串对比不能使用==/!=,该运算符对比的是字符串对象的内存地址,不是文本内容,需使用equals()或contains()方法判断内容
  • Selenium的getAttribute("src")返回的是完整绝对路径,而非页面源码里写的相对路径,比如站点部署在http://127.0.0.1:8080下,返回结果会是http://127.0.0.1:8080/name_red.png,直接匹配短文件名必然失败
  • 原代码判断条件误写了不存在的目标文件名name_red2.png,和页面onclick事件触发修改的name_red.png不一致

实现方案1:直接判断src属性包含目标文件名

WebElement red = driver.findElement(By.id("aa"));
red.click();
// 显式等待1秒,比Thread.sleep更节省时间,元素就绪就会继续执行
new WebDriverWait(driver, Duration.ofSeconds(1)).until(
    webDriver -> webDriver.findElement(By.id("aa")).getAttribute("src").contains("name_red.png")
);
String src = driver.findElement(By.id("aa")).getAttribute("src");

if (src.contains("name_red.png")) {
    System.out.println("Image is red now");
} else {
    System.out.println("It didn't work");
}

实现方案2:通过css选择器判断元素是否存在

WebElement red = driver.findElement(By.id("aa"));
red.click();
boolean isSwitched;
try {
    // 等待匹配src的元素出现,超时1秒
    new WebDriverWait(driver, Duration.ofSeconds(1)).until(
        ExpectedConditions.presenceOfElementLocated(By.cssSelector("img#aa[src*='name_red.png']"))
    );
    isSwitched = true;
} catch (TimeoutException e) {
    isSwitched = false;
}

if (isSwitched) {
    System.out.println("Image is red now");
} else {
    System.out.println("It didn't work");
}

注意:如果使用Selenium 3及更低版本,Duration.ofSeconds(1) 替换为数字1即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 19:06:08