Identify Broken Links

Broken links are links or URLs that are not reachable. They may be down or not functioning due to some server error. It is always necessary that there are no broken links on the site because the user should not land into an error page.

 

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrokenLinks {

public static void main(String[] args) {

// Telling Selenium to find Chrome Driver
System.setProperty("webdriver.chrome.driver", "C:\selenium\chromedriver.exe");

// Initialize browser
ChromeDriver driver = new ChromeDriver();

// Maximize Browser Window
driver.manage().window().maximize();

// Launch Tequality Demo
driver.get("https://demoapp1.tequality.tech/");

// Storing all the 'a' tags in a Array List
List<WebElement> links = driver.findElements(By.tagName("a"));

for (int i = 0; i <= links.size(); i++) {
try {

// Iterating through the array list and getting the URL's
String nextHref = links.get(i).getAttribute("href");

// Getting the Response Code for URL
URL url = new URL(nextHref);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();

// Condition to check whether the URL is valid or Invalid
if (code == 200)
System.out.println("Valid Link:" + nextHref);

else
System.out.println("INVALID Link:" + nextHref);

} catch (Exception e) {
System.out.println(e.getMessage());
}
}
driver.quit();
}
}