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
相关产品推荐
相关产品推荐

