public String getRightUrlBaseOnUrl(String nowUrl , String baseUrl) {
//定义结果
String result = "";
//如果是http开头就是结果
if(nowUrl.startsWith("http")) {
result = nowUrl ;
} else {
//如果是以../开头 , 需要统计../的个数
if(nowUrl.startsWith("../")) {
//定义../的正则
Pattern p = new Pattern("\\.\\./");
//使用正则匹配原url
Matcher matcher = p.matcher(nowUrl);
//定义个数
int count = 0 ;
while(matcher.find()) {
//如果发现则计数加1
count ++;
}
//对referer进行初始化 加入baseUrl为http://www.sina.com.cn/joy/hello/nihao.html , 则初始化为http://www.sina.com.cn/joy/hello
String baseUrlBack = baseUrl.substring(0, baseUrl.lastIndexOf("/"));
//然后向前查找count个斜杠
for (int i = 1; i <= count; i++) {
baseUrlBack = baseUrlBack.substring(0, baseUrlBack.lastIndexOf("/"));
}
//将nowUrl中的../替换掉
while(nowUrl.startsWith("../")) {
nowUrl = nowUrl.replace("../", "");
}
//将两个结果合并起来
result = baseUrlBack + "/" + nowUrl;
} else {
//不以http开头 , 也不以../开头
//对referer进行初始化 加入baseUrl为http://www.sina.com.cn/joy/hello/nihao.html , 则初始化为http://www.sina.com.cn/joy/hello
String baseUrlBack = baseUrl.substring(0, baseUrl.lastIndexOf("/"));
//将两个结果合并起来
result = baseUrlBack + "/" + nowUrl;
}
}
return result;
}
抓网页时常用的得到正确的超链接和图片地址的方法
最新推荐文章于 2024-09-18 10:16:18 发布