在用爬虫解析页面的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;
}