[Java] 网页相对URL解析

来源:互联网 发布:hashmap源码 编辑:程序博客网 时间:2024/04/29 17:29

在用爬虫解析页面的URL时,经常会碰到存在相对URL的情况,比如包含/、./和../的情况,需要做转换:

/**     * 解析网页中的相对URL     * @param link 网页中的链接,如href     * @param sourceUrl 网页自身的URL     * @return 转换后的URL     */    public static String convertLinkToUrl(String link, String sourceUrl) {        String url = link;        if (!link.matches("http://.*") && !link.matches("https://.*")) {            // 截取原始URL中最后一个“/”之前的内容,            int lastSeparatorIndex = sourceUrl.lastIndexOf("/");            String thisUrl = sourceUrl;            if(lastSeparatorIndex > 0) {                thisUrl = sourceUrl.substring(0,lastSeparatorIndex);            }            // 处理相对路径            while(link.startsWith("/") || link.startsWith(".")) {                if(link.startsWith("./")) {                    link = link.replace("./","");                }                if(link.startsWith("/")) {                    link = link.replace("/","");                }                if(link.startsWith("../")) {                    link = link.replace("../","");                    lastSeparatorIndex = thisUrl.lastIndexOf("/");                    if(lastSeparatorIndex > 0) {                        thisUrl = sourceUrl.substring(0,lastSeparatorIndex);                    }                }            }            // 合成最终的绝对路径            url = thisUrl + "/" + link;        }        return url;    }


0 0
原创粉丝点击