首页 > 解决方案 > 使用 selenium java 验证 Web 中的图像/徽标存在失败

问题描述

我是 Selenium 的新手。在这种情况下,我想验证此 guru99 网页中的图像/徽标以供我自己启用。我已经尝试使用 xpath 查找元素,但输出显示没有显示图像。除了查找元素之外,还有其他方法可以验证此图像吗?请参考以下检查:

检查图像元素

这是代码(请参阅“验证图像”评论后:

@Test
        public void testParameterWithXML() throws InterruptedException, AWTException{
            driver.get("http://demo.guru99.com/V4/");
            //Find user name
            WebElement userName = driver.findElement(By.name("uid"));
            //Fill user name
            userName.sendKeys("guru99");
            //Find password
            WebElement password = driver.findElement(By.name("password"));
            //Fill password
            password.sendKeys("guru99");
            //Press enter
            //driver.findElement(By.name("btnLogin")).click();
            
            //add verification -img, texts
            
            //verify title
            Boolean verifyTitle = driver.getTitle().equalsIgnoreCase("Guru99 Bank Home Page");
            System.out.println(verifyTitle);
            assertTrue(verifyTitle);
            
            //verify text demo site
            //WebElement demosite = driver.findElement(By.className("site-name"));
            //System.out.println(demosite);
            
            //verify image
            WebElement ImageFile = driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[1]/div[1]/a/img"));
            Boolean ImagePresent = (Boolean) ((JavascriptExecutor)driver).executeScript("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", ImageFile);
    
            if (!ImagePresent)
            {
            System.out.println("Image displayed.");
            }
            else
            {
            System.out.println("Image not displayed.");
            }
            
            
        }

这就是结果。仅供参考,我使用跨浏览器测试运行我的测试,我一次在 3 个浏览器中运行所有测试。因此,测试运行 = 3。 true 用于验证标题(这里不是问题),但对于图像,它被认为是失败的,因为它无法验证存在的图像:

测试结果

标签: seleniumselenium-webdriverautomated-testsselenium-chromedriver

解决方案


推荐阅读