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);