Total Pageviews

Monday, 3 December 2018

How to verify broken images on a webpage using selenium

Have you ever faced a situation where you were asked to verify all the images present on a webpage and weather they are broken or visible.

Here is a way to do this using selenium using HttpURLConnection class of Java.


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
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 ImageTest {

    public static void main(String[] args) {

        System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        List<WebElement> list = driver.findElements(By.tagName("img"));
        System.out.println("Total number of Images on webpage:---->>" + list.size());

        for (WebElement ele : list) {
            try {
                HttpURLConnection conn = (HttpURLConnection) new URL(ele.getAttribute("src")).openConnection();
                conn.setRequestMethod("GET");
                int responceCode = conn.getResponseCode();
                if (responceCode != 200) {
                    System.out.println("Broken Image:---->>" + ele.getAttribute("src"));
                } else {
                    System.out.println("Fine Image:------->>" + ele.getAttribute("src"));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        driver.close();
    }
}








Save Water | Save Energy | Save Earth     
    Stop Pollution | Stop Plastic
                 Spread Peace

5 comments:

  1. Great video. Thanks for sharing. Could you please explain how to handle it when all the images are broken?

    ReplyDelete
  2. Could not thank you more than enough for the posts on your web-site. I know you placed a lot of time and energy into all of them and really hope you know how considerably I enjoy it. I hope I will do something identical for another individual at some point. my sources

    ReplyDelete
  3. The blog writings were so nice, I wished they neever ended.
    Automation testing

    ReplyDelete
  4. The writer has so beautifully captivated the attention of audience by this resplendent blog.
    alpinestars gloves

    ReplyDelete
  5. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. phone number for verification

    ReplyDelete