Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Malformed exception in Selenium WebDriver using Java to find the broken links

I am using this code in Selenium script to find the broken links. So this is the code I have written but on running I am getting the malformed exception.

public void countNoOfLinksInHomePage(WebDriver fd) throws IOException{
        List<WebElement> listOfElements=fd.findElements(By.tagName("a"));
        //System.out.println(listOfElements.get(0));
        //log.info("name of links is " +listOfElements);
        int countOfElements=listOfElements.size();
        log.info("Total no of links in Homepage is:: " +countOfElements);

        //for(int i=0;i<countOfElements;i++){

            int responseCode=getResponseCode(listOfElements.get(1).getAttribute("href"));
            log.info("Response code of element at index 1 is:: " + responseCode);

            //break;
        //}
    }

    public static int getResponseCode(String url) throws MalformedURLException, IOException{

        URL u=new URL(url);
        HttpURLConnection huc=(HttpURLConnection)u.openConnection();
        huc.setRequestMethod("GET");
        huc.connect();
        return huc.getResponseCode();
    }

The testng trace is :

java.net.MalformedURLException: unknown protocol: javascript

like image 454
Adam Grunt Avatar asked Sep 26 '22 14:09

Adam Grunt


1 Answers

The page contains anchors with a javascript href:

<a href="javascript:..." 

It does not make sense to test these links, therefore filter them as below code snippet:

String href = listOfElements.get(1).getAttribute("href");
if ((href != null) && !href.startsWith("javascript")) {
    int responseCode=getResponseCode(href);
    log.info("Response code of element at index 1 is:: " + responseCode);
}
like image 169
wero Avatar answered Sep 28 '22 07:09

wero