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

本文介绍了一种将网页中的相对URL转换为绝对URL的方法。通过解析网页源地址并结合相对路径规则,实现链接的有效转换。
2419

被折叠的 条评论
为什么被折叠?



