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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With