Search code examples
imageseleniumtestingautomationtitle

Not able to list images whose title attribute is missing in selenium


Below is my code i am trying to get src of image whose title attribute is missing but its not working. With below code all images are displayed but its not searching for image without title

public void checkimagetitle() {

    suites.setupEnviroment();
    WebDriver driver = suites.getWebDriver();
    driver.get(suites.WEB_PATH);
    Dimension d = new Dimension(1455, 900);
    driver.manage().window().setSize(d);

    try {
        List<WebElement> listImages = driver.findElements(By.tagName("img"));

        System.out.println("No. of Images: " + listImages.size());

        int counter = 0;
        for (WebElement image : listImages) {
            boolean title = image.getAttribute("title") != null;

            if (title = false) {
                counter++;
                System.out.println(image.getAttribute("src"));
            } else {
                System.out.println("failed");

            }
        }
        System.out.println("No. of total images without title: " + counter);

        Logger.getLogger("results").log(new LogRecord(Level.INFO,
                MethodHandles.lookup().lookupClass().getCanonicalName() != null ? "success" : "failure"));

    } catch (Exception e) {
        Logger.getLogger("results").log(new LogRecord(Level.INFO,
                MethodHandles.lookup().lookupClass().getCanonicalName() == null ? "success" : "failure"));
        System.out.println(e);
    }
    driver.close();

}

Thanks in advance!


Solution

  • Found a simpler solution. Rather than looping through all the images, you can directly detect img elements without title attribute by using XPATH like

    //img[not(@title)]
    List<WebElement> listImageswithoutTitle = driver.findElements(By.xpath("//img[not(@title)]"));