Groovy脚本检查html坏链接

这些天在搞Gradle翻译,因为原译者在翻译的同时也把文件进行了整理,并且把翻译过的章节放到新的文件夹中,导致可能有些超链接未改正过来变成死链接。

本想在网上找个工具来检查的,百度了几个工具要么太大要么要安装,懒得弄那么多,于是用Groovy写了一个脚本。此脚本仅检查本地超链接,代码如下:

if (args.size() != 1) {
    printf("Please specify a folder or HTML file path...")
    return
}

def file = new File(args[0])
if(file.isFile()) {
    if(!args[0].toLowerCase().endsWith(".html")) {
        return
    }
    checkHtml(file)
} else if (file.isDirectory()) {
    def errorLinks = new HashMap<String, List<String>>()
    file.eachFileMatch( ~/.*\.html/, {
        checkHtml(it, errorLinks)
    })
    errorLinks.each {name, links ->
        println "file: " + name
        links.each {
            println "href:\t" + it
        }
    }
}

void checkHtml(File file, HashMap<String, List<String>> errorlinks) {
    def matches = file.text.findAll('href="([^#(http)].+?)("|#)')
    def links = new ArrayList<String>()
    matches.each {
        def path = it - 'href="' - '"' - '#'
        if(!new File(file.getParentFile(), path).exists()) {
            links.add(path)
        }
    }
    if(!links.isEmpty()) {
        errorlinks.put(file.path, links)
    }
}

运行时传入一个地址。如果是HTML文件,则检查该文件。如果是目录,则检查里面的HTML文件,其他文件不检查。然后把有错误的文件及其超链接在最后打印出来,正确的不打印。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。