我目前正在使用JTidy解析一个超文本标记语言文档,并获取给定超文本标记语言文档中所有锚标记的集合。然后,我提取每个标记的href属性的值,以得到页面上的链接集合。
不幸的是,这些链接可以用几种不同的方式来表示:一些是绝对的(http://www.example.com/page.html),一些是相对的(/page.html、page.html或../page.html)。更重要的是,有些只是锚(#paragraphA)。当我在浏览器中访问我的页面时,如果我单击链接,它会自动知道如何处理这些不同的href值,但是如果我要使用HTTPClient以编程方式使用从JTidy检索到的这些链接之一,我首先需要提供一个有效的URL (因此,我首先需要将/page.html、page.html和http://www.example.com/page.html转换为http://www.example.com/page.html)。
有没有一些内置的功能,无论是在JTidy中还是在其他地方,都可以为我实现这一点?或者我需要创建自己的规则来将这些不同的URL转换为绝对URL?
发布于 2011-12-20 08:16:07
假设您能够确定要使用的上下文,那么普通URL类可能会帮助您完成大部分工作。下面是一些示例:
package grimbo.url;
import java.net.MalformedURLException;
import java.net.URL;
public class TestURL {
public static void main(String[] args) {
// context1
URL c1 = u(null, "http://www.example.com/page.html");
u(c1, "http://www.example.com/page.html");
u(c1, "/page.html");
u(c1, "page.html");
u(c1, "../page.html");
u(c1, "#paragraphA");
System.out.println();
// context2
URL c2 = u(null, "http://www.example.com/path/to/page.html");
u(c2, "http://www.example.com/page.html");
u(c2, "/page.html");
u(c2, "page.html");
u(c2, "../page.html");
u(c2, "#paragraphA");
}
public static URL u(URL context, String url) {
try {
URL u = null != context ? new URL(context, url) : new URL(url);
System.out.println(u);
return u;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
}结果如下:
http://www.example.com/page.html
http://www.example.com/page.html
http://www.example.com/page.html
http://www.example.com/page.html
http://www.example.com/../page.html
http://www.example.com/page.html#paragraphA
http://www.example.com/path/to/page.html
http://www.example.com/page.html
http://www.example.com/page.html
http://www.example.com/path/to/page.html
http://www.example.com/path/page.html
http://www.example.com/path/to/page.html#paragraphA正如您所看到的,有些结果并不是您想要的。因此,您可能会先尝试使用new URL(value)解析URL,如果结果是MalformedURLException,则可以尝试相对于上下文URL。
发布于 2011-12-20 07:57:44
最好的解决方案很可能遵循与浏览器相同的解析过程,就像outlined in the HTML spec一样
用户代理必须按照以下优先级(从高优先级到低优先级)计算基本URI:
在实践中,您最关心的可能是数字1和2(即检查<base href="..."并使用该URI (如果存在)或当前文档的URI)。
https://stackoverflow.com/questions/8568976
复制相似问题