How can I find broken or invalid images on a webpage using Webdriver?

0 votes
How can I find broken or invalid images on a webpage using Webdriver?
Jul 2 in Selenium by Lucy
19 views

1 answer to this question.

0 votes

Hey @Lucy, to find the broken or invalid images links on a webpage you can use HTTPClient library to check status codes of the images on a page. If they don't load correctly, then it will be registered with likely a 404 but not a 200 status code. We can easily say tell whether the link is broken or not with status codes. If the status code is 404, then image link is invalid/broken. You can try this code snippet to find broken images:

int invalidImageCount = 0; 

WebDriver driver = new FirefoxDriver(); 
driver.get("http://google.com");

List<WebElement> imagesList = driver.findElements(By.tagName("img")); 
System.out.println("Total no. of images are " + imagesList.size()); 

for (WebElement imgElement : imagesList) { 
 if (imgElement != null) { 
  try { 
   HttpClient client = HttpClientBuilder.create().build(); 
   HttpGet request = new HttpGet(imgElement.getAttribute("src")); 
   HttpResponse response = client.execute(request); 

   // verifying response code he HttpStatus should be 200 if not, 
   // increment as invalid images count 

   if (response.getStatusLine().getStatusCode() != 200) 
     invalidImageCount++; 
   } catch (Exception e) { 
     e.printStackTrace(); 
   }
  } 
 } 

System.out.println("Total no. of invalid images are " + invalidImageCount);
answered Jul 3 by Junaid

Related Questions In Selenium

0 votes
1 answer

How can I verify Error Message on a webpage using Selenium Webdriver?

Hey Hansraj, to verify an error message ...READ MORE

answered 2 days ago in Selenium by Abha
• 16,440 points
14 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Finding WebDriver element with Class Name in java

The better way to handle this element ...READ MORE

answered Apr 10, 2018 in Selenium by nsv999
• 5,050 points
259 views
0 votes
1 answer
0 votes
1 answer

Geo-location microphone camera pop up

To Allow or Block the notification, access using Selenium and you have to ...READ MORE

answered May 11, 2018 in Selenium by Samarpit
• 5,130 points
628 views
0 votes
1 answer

How to use such xpath to find web elements

It's much simpler to use: #MyDiv123 > div.super or ...READ MORE

answered Jun 14, 2018 in Selenium by Samarpit
• 5,130 points
257 views
0 votes
1 answer