简体   繁体   中英

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

How to count number of images available on a web page using selenium webdriver? The web page contains a lots of image some are visible and some are hidden (display:none). I only wants to count images which are visible(not hidden).

I tried this but it doesn't work for only 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);
    }

You need to apply isDisplayed() check on each image element in the loop:

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

Here you wanted to find out the no. of images in a page, so better check with tag name like 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();

    }
package p1;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CountImages {
     public static void main(String[] args) {
         System.setProperty("webdriver.gecko.driver","/home/mcastudent/Downloads/software/geckodriver" );
         WebDriver driver=new FirefoxDriver();
         driver.get("https://opensource-demo.orangehrmlive.com/index.php/dashboard");
         List<WebElement> listImages=driver.findElements(By.tagName("img"));
         System.out.println("No. of Images: "+listImages.size());

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM