URL Selenium WebDriver 中使用 Java 查找损坏链接的异常

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

我在 Selenium 脚本中使用这段代码来查找损坏的链接。所以这是我写的代码,但是在 运行 我得到了格式错误的异常。

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();
    }

testng 跟踪是:

java.net.MalformedURLException:未知协议:javascript

该页面包含具有 javascript href 的锚点:

<a href="javascript:..." 

测试这些链接没有意义,因此按以下代码片段过滤它们:

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);
}