標籤: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檔案,其他檔案不檢查。然後把有錯誤的檔案及其超連結在最後列印出來,正確的不列印。
Groovy指令碼檢查html壞連結