java - Selenium WebDriver 中的 URL Malformed 异常使用 Java 查找断开的链接

标签 java selenium selenium-webdriver 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: 未知协议(protocol): javascript

最佳答案

该页面包含带有 javascript href 的 anchor :

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

关于java - Selenium WebDriver 中的 URL Malformed 异常使用 Java 查找断开的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35012287/

相关文章:

python - Selenium 显式等待 invisibility_of_element() 根本不等待

java - Elasticsearch 匹配完整的术语数组

java - 未找到 Spring 应用程序上下文

java - 使用 Selenium Java 从 HTML 中获取字符串文本

c# - 我如何使用 Selenium WebDriver 在后台打开 chrome 新标签窗口?

java - 如何将 ant 参数传递给 junit/selenium 测试?

java - 使用java执行shell命令

java - 值溢出指定精度 0,小数位数 0

javascript - 如何使用 Selenium WebDriver 和 Java 从元素中检索文本

python - 写入 selenium 数据时 CSV 为空