Verify broken links using Web driver




import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrokenLinks {
    public static int invalidLink;
    String currentLink;
    String temp;
    public static void main(String[] args) throws IOException {
       //Launch The Browser
        WebDriver driver=new FirefoxDriver();
        //Enter Url
        driver.get("http://www.excellenceq.com");
        //Get all the links url
        List<WebElement> ele=driver.findElements(By.tagName("a"));
        System.out.println("size:" +ele.size() );
        for(int i=0;i<ele.size();i++) {
            System.out.println(ele.get(i).getAttribute("href"));
            int statusCode=0;
            try{
            statusCode=getResponseCode(ele.get(i).getAttribute("href"));
            }catch(Exception e)
            {
                e.printStackTrace();
            }
            if(statusCode==404) {
                System.out.println("InvalidLink ********** :"+ele.get(i).getAttribute("href"));
            }else {
                System.out.println(":ValidLinks:"+ele.get(i).getAttribute("href"));
            }
        }


    }
    //The below script will identify all the broken links(if any) in excelenceq.com and store the 404 URLs in List. It verifies the server status, any links giving 404 status.
    public static int getResponseCode(String urlString) throws IOException{
        URL u = new URL(urlString);
        HttpURLConnection h =  (HttpURLConnection)  u.openConnection();
        h.setRequestMethod("GET");
        h.connect();
        return h.getResponseCode();
    }

}

Manoj Kumar
manojqa5006@gmail.com