Automate Finding Broken Images with Selenium-Java
Kushal Parikh
QA Automation Engineer | SDET | Test Automation Consultant | Selenium | Java | Playwright | SFPC? Certified | Driving Quality Through Automation
When developing web applications, ensuring that all images load correctly is crucial for maintaining a good user experience. Broken images can frustrate users and reflect poorly on your site. In this blog post, we’ll walk through a simple Selenium test using Java to identify broken images on a webpage.
Why Test for Broken Images?
Images are a key component of web design, influencing both aesthetics and functionality. If an image fails to load, it can disrupt the flow of content and lead to a negative impression. Automated tests help catch these issues early in the development process.
Note: Ensure you have the necessary libraries installed, such as Selenium and TestNG.
The Code
Here’s a simple example of a Selenium test that checks for broken images on a specific webpage:
领英推荐
package LambdaTest_PlagroundSolution;
import Selenium_Utilities.PageLocatorActions;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import static org.testng.AssertJUnit.fail;
public class BrokenImages_Test extends PageLocatorActions {
private static String url = "https://www.lambdatest.com/selenium-playground/broken-image";
private static int iBrokenImageCount = 0;
@BeforeTest
public void setup() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(25));
driver.manage().deleteAllCookies();
}
@AfterTest
public void teardown() {
if (driver != null) {
driver.quit();
}
}
@Test
public void VerifyBrokenImages() {
driver.get(url);
try {
iBrokenImageCount = 0;
List<WebElement> image_list = getElementsLists("https://div[@class='learn_right']//img");
/* Print the total number of images on the page */
System.out.println("The page under test has " + image_list.size() + " images");
for (WebElement img : image_list) {
if (img != null) {
String src = img.getAttribute("src");
if (isImageBroken(src) || (img.getAttribute("naturalWidth").equals("0") && img.getAttribute("naturalHeight").equals("0"))) {
System.out.println(img.getAttribute("outerHTML") + " is broken.");
iBrokenImageCount++;
}
}
}
System.out.println("The page " + url + " has " + iBrokenImageCount + " broken images");
} catch (Exception e) {
fail("Test is failed due to : " + e.getMessage());
}
}
private boolean isImageBroken(String imageUrl) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();
connection.setRequestMethod("HEAD");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
int responseCode = connection.getResponseCode();
return responseCode == 404 || responseCode >= 400; // Check for 404 and any 4xx or 5xx errors
} catch (IOException e) {
return true; // Treat any exception as a broken image
}
}
}
Code Breakdown
1. Setup and Teardown: The setup method initializes the Chrome browser, while the teardown method closes it after the test.
2. Image Verification: The VerifyBrokenImages method navigates to the test page, retrieves all image elements, and checks each image for loading issues.
3. Checking Image Status: For each image, use HttpURLConnection to send a HEAD request to check if the image URL returns an error (e.g., 404). Additionally, check the naturalWidth and naturalHeight attributes; if both are "0", the image is considered broken.
Automating tests for broken images is a straightforward process that can save you time and improve your web application’s reliability. By using the Selenium framework and the above code, you can quickly identify issues with image loading and ensure a smoother experience for your users.
Happy testing!
QA Automation Engineer
1 个月Very helpful
"Senior QA Lead with 10+ Years of Experience | Mastering Excellence in Software Quality & Elevating Team Dynamics"
1 个月Awesome Explanation