我目前正在使用 JTidy 来解析 HTML 文档并获取给定 HTML 文档中所有 anchor 标记的集合。然后,我提取每个标签的 href 属性的值,以在页面上生成一组链接。
不幸的是,这些链接可以用几种不同的方式表示:一些是绝对的(http://www.example.com/page.html
),一些是相对的(/page.html)。 html
、page.html
或 ../page.html
)。更重要的是,有些可以只是 anchor (#paragraphA
)。当我在浏览器中访问我的页面时,如果我单击链接,它会自动知道如何处理这些不同的 href 值,但是如果我要使用 HTTPClient 以编程方式跟踪从 JTidy 检索到的其中一个链接,我首先需要提供一个有效的 URL(例如,我首先需要将/page.html、page.html 和 http://www.example.com/page.html 转换为 http://www.example.com/page.html)。
是否有一些内置功能(无论是在 JTidy 中还是在其他地方)可以为我实现此目的?或者我是否需要创建自己的规则来将这些不同的 URL 转换为绝对 URL?
最佳答案
假设您可以确定要使用的上下文, Vanilla 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。
关于java - 使用 JTidy 解析链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8568976/