Contents

    Guides

    Handling Broken Links & Broken Images in Selenium

    Published on

    September 11, 2025
    Handling Broken Links & Broken Images in Selenium

    It's crucial to ensure that web applications perform flawlessly across all browsers and devices. One important aspect of web functionality is verifying that all links and images are functioning correctly. 

    Broken links and images can negatively affect the user experience and site performance. Selenium WebDriver, a popular automation tool, offers an effective solution to identify and resolve these issues.

    How to Identify Broken Links Using Selenium WebDriver

    Selenium WebDriver automates the process of detecting broken links by interacting with the webpage and checking the HTTP response of each link. Here’s a basic workflow:

    • Use Selenium to extract all links on the page.
    • Send an HTTP request for each link to verify the response code.
    • Log or report any links that return a status code indicating they are broken (e.g., 404, 403).

    Example: Identifying Broken Links with Selenium

    Here is an example in Java that demonstrates how to detect broken links using Selenium WebDriver:

    import org.openqa.selenium.WebDriver;

    import org.openqa.selenium.chrome.ChromeDriver;

    import org.openqa.selenium.By;

    import org.openqa.selenium.WebElement;

    import java.net.HttpURLConnection;

    import java.net.URL;

    import java.util.List;

    public class BrokenLinksTest {

        public static void main(String[] args) {

            System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

            WebDriver driver = new ChromeDriver();

            driver.get("http://example.com");

            List<WebElement> links = driver.findElements(By.tagName("a"));

            for (WebElement link : links) {

                String url = link.getAttribute("href");

                verifyLink(url);

            }

            driver.quit();

        }

        public static void verifyLink(String linkUrl) {

            try {

                HttpURLConnection connection = (HttpURLConnection) new URL(linkUrl).openConnection();

                connection.setRequestMethod("HEAD");

                connection.connect();

                int responseCode = connection.getResponseCode();

                if (responseCode >= 400) {

                    System.out.println("Broken link: " + linkUrl + " Response Code: " + responseCode);

                } else {

                    System.out.println("Working link: " + linkUrl + " Response Code: " + responseCode);

                }

            } catch (Exception e) {

                System.out.println("Invalid link: " + linkUrl);

            }

        }

    }

    This code uses Selenium to find all anchor (<a>) tags on the page. For each link, it sends an HTTP HEAD request to verify its validity. If the response code is 400 or higher, the link is flagged as broken.

    What are Broken Images and How to Identify Them in Selenium?

    Broken images occur when an image fails to load due to issues such as incorrect file paths, server problems, or missing resources. This typically results in a placeholder image being displayed. Detecting broken images with Selenium is similar to detecting broken links, where we validate the src attribute and check the HTTP status.

    Identifying Broken Images Using Selenium

    To detect broken images, you need to:

    • Extract all image elements (<img>) on the page using Selenium.
    • Verify the src attribute for each image.
    • Make an HTTP request to validate whether the image URL is working.

    Example: Detecting Broken Images in Selenium

    Here is an example in Java to detect broken images using Selenium:

    import org.openqa.selenium.WebDriver;

    import org.openqa.selenium.chrome.ChromeDriver;

    import org.openqa.selenium.By;

    import org.openqa.selenium.WebElement;

    import java.net.HttpURLConnection;

    import java.net.URL;

    import java.util.List;

    public class BrokenImagesTest {

        public static void main(String[] args) {

            System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

            WebDriver driver = new ChromeDriver();

            driver.get("http://example.com");

            List<WebElement> images = driver.findElements(By.tagName("img"));

            for (WebElement image : images) {

                String imageUrl = image.getAttribute("src");

                verifyImage(imageUrl);

            }

            driver.quit();

        }

        public static void verifyImage(String imageUrl) {

            try {

                HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();

                connection.setRequestMethod("HEAD");

                connection.connect();

                int responseCode = connection.getResponseCode();

                if (responseCode >= 400) {

                    System.out.println("Broken image: " + imageUrl + " Response Code: " + responseCode);

                } else {

                    System.out.println("Working image: " + imageUrl + " Response Code: " + responseCode);

                }

            } catch (Exception e) {

                System.out.println("Invalid image: " + imageUrl);

            }

        }

    }

    In this example, Selenium finds all images on the page and verifies their src attribute by sending an HTTP HEAD request. If the response code is 400 or higher, the image is considered broken.

    Why Use Real Devices to Test Broken Links?

    Testing for broken links on real devices offers key advantages over emulators:

    • Accurate User Experience: Real devices replicate actual browsing conditions, including network variability and device-specific behavior, ensuring a more reliable test of how links perform under real-world circumstances.
    • Device-Specific Behavior: Real devices account for browser differences across OS and screen sizes, revealing issues that may not appear on emulators.
    • Performance Insights: Test load times, broken link response, and handling under real network conditions, providing a true reflection of user experience.
    • Cross-Platform Compatibility: Testing across a range of real devices ensures your site works seamlessly across various browsers and operating systems.

    Emulators often fall short in replicating true user behavior, but testing platforms like BrowserStack Automate enables you to run Selenium tests on real devices in the cloud, offering precise, reliable results across different environments without the need to maintain physical devices.

    Conclusion

    Ensuring all links and images on your website are functional is essential for maintaining a positive user experience and improving SEO. 

    Selenium WebDriver offers an easy and effective way to automate the detection of broken links and images. By integrating these checks into your Selenium tests, you can ensure your website is free of broken resources. 

    For even more robust testing, consider using testing tools like BrowserStack Automate. It allows you to run tests on a range of real devices and browsers, helping ensure your application works across all environments and provides reliable performance for users.

    Run Selenium Tests on Cloud

    Data-rich bug reports loved by everyone

    Get visual proof, steps to reproduce and technical logs with one click

    Make bug reporting 50% faster and 100% less painful

    Rating LogosStars
    4.6
    |
    Category leader

    Liked the article? Spread the word

    Put your knowledge to practice

    Try Bird on your next bug - you’ll love it

    “Game changer”

    Julie, Head of QA

    star-ratingstar-ratingstar-ratingstar-ratingstar-rating

    Overall rating: 4.7/5

    Try Bird later, from your desktop