这里说的相对路径是网络上的链接路径。
我现在的解决方法是//相对路径转绝对路径
private String makeAbsoluteURL(URL strWeb, String innerURL) {
// TODO Auto-generated method stub
if (innerURL != null
&& innerURL.toLowerCase().startsWith("http://")) {
return innerURL;
}
URL linkUri = null;
try {
linkUri = new URL(strWeb, innerURL);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return linkUri.toString();
}但是这种方法无法处理下面的情况
比如,
strWeb = "http://456.e.now.cn/";
innerURL = "../share/style.css";java有没有直接可以用的处理方法,不想自己写函数实现,很麻烦,也容易出错。
我现在的解决方法是//相对路径转绝对路径
private String makeAbsoluteURL(URL strWeb, String innerURL) {
// TODO Auto-generated method stub
if (innerURL != null
&& innerURL.toLowerCase().startsWith("http://")) {
return innerURL;
}
URL linkUri = null;
try {
linkUri = new URL(strWeb, innerURL);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return linkUri.toString();
}但是这种方法无法处理下面的情况
比如,
strWeb = "http://456.e.now.cn/";
innerURL = "../share/style.css";java有没有直接可以用的处理方法,不想自己写函数实现,很麻烦,也容易出错。
若:(见楼主贴子)比如,
strWeb = "http://456.e.now.cn/";
innerURL = "../share/style.css";
请问:你这个方法能把楼主的相对innerURL转变成绝对:http://456.e.now.cn/share/style.css吗?
如在:WEB网页爬虫程序中,其获取的网页地址是:strWeb = "http://456.e.now.cn/";
而:innerURL = "../share/style.css"; 是该网页中抓出来的相对URL,你这个方法能变成:上边的绝对URL吗?
一句话:我想恐怕要楼主自己写了。
转换代码如下:URI base=new URI("http://456.e.now.cn/test/");//基本网页URI
URI abs=base.resolve("../share/style.css");//解析于上述网页的相对URL,得到绝对URI
URL absURL=abs.toURL();//转成URL
System.out.println(absURL);运行结果:http://456.e.now.cn/share/style.css
URI abs=base.resolve("../share/style.css");//解析于上述网页的相对URL,得到绝对URI
URL absURL=abs.toURL();//转成URL
System.out.println(absURL);
答:基本页面URL:http://456.e.now.cn/
相对于上述基本页面的URL:../share/style.css 这个相对URL是不正确的故当然不行。错误原因是:../share/style.css 这个红色的..表示相对于基本页面的父亲(而:这个基本页面的父亲是不存在的),而若:基本页面URL是:http://456.e.now.cn/test/,则这个页面的父亲是存在的。故我12楼的才有运行结果。
做爬虫的话,上面的处理可能还不够吧,因为html有个属性 base ,楼主是不是也要注意这个设置呢?