加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy脚本检查html坏链接

发布时间:2020-12-14 16:49:18 所属栏目:大数据 来源:网络整理
导读:这些天在搞Gradle翻译,因为原译者在翻译的同时也把文件进行了整理,并且把翻译过的章节放到新的文件夹中,导致可能有些超链接未改正过来变成死链接。 本想在网上找个工具来检查的,百度了几个工具要么太大要么要安装,懒得弄那么多,于是用Groovy写了一个脚

这些天在搞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文件,其他文件不检查。然后把有错误的文件及其超链接在最后打印出来,正确的不打印。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读