How to count the number of images available on a web page using selenium webdriver?

How to count the number of images available on a web page using selenium webdriver? The web page contains many images, some of them are visible and some are hidden (display: none). I just want to count images that are visible (not hidden).

I tried this, but it does not work only for visible images.

@Test
    public void imagetest()
    {
        driver.get("http://uat.tfc.tv/");
        List<WebElement> listwebelement = driver.findElements(By.className("img-responsive"));
        int i=0;
        for (WebElement Element : listwebelement) {
            i = i+1;
            System.out.println(Element.getTagName());
            System.out.println(Element.getText());

            String link = Element.getAttribute("alt");

            System.out.println(link);
        }
        System.out.println("total objects founds " + i);
    }
+4
source share
2 answers

Here you would like to find out no. images per page, so it’s best to check with the tag name as shown below:

driver.findElements(By.tagName("img")

Here is the complete code for your reference.

@Test
    public void findNoOfDisplayeImages() throws InterruptedException
    {
        WebDriver driver=new FirefoxDriver();
        Integer counter=0;
        driver.get("http://uat.tfc.tv/");
        Thread.sleep(20000);
        List<WebElement> listImages=driver.findElements(By.tagName("img"));
        System.out.println("No. of Images: "+listImages.size());
        for(WebElement image:listImages)
        {
            if(image.isDisplayed())
            {
                counter++;
                System.out.println(image.getAttribute("alt"));
            }
        }
        System.out.println("No. of total displable images: "+counter);
        driver.close();

    }
+1
source

isDisplayed() :

for (WebElement Element : listwebelement) {
    if (!Element.isDisplayed()) {
        continue;
    }
    ...
}
+1

Source: https://habr.com/ru/post/1548624/


All Articles