jsoup - 使用 URL
以下示例将展示可以提供 html 页面中存在的相对和绝对 URL 的方法。
语法
String url = "http://www.tutorialspoint.com/"; Document document = Jsoup.connect(url).get(); Element link = document.select("a").first(); System.out.println("Relative Link: " + link.attr("href")); System.out.println("Absolute Link: " + link.attr("abs:href")); System.out.println("Absolute Link: " + link.absUrl("href"));
其中
document − document 对象表示 HTML DOM。
Jsoup − 主类用于连接到 url 并获取 html 内容。
link − Element 对象表示代表锚标记的 html 节点元素。
link.attr("href") − 提供锚标记中 href 的值。它可以是相对的,也可以是绝对的。
link.attr("abs:href") − 在根据文档的基本 URI 解析后提供绝对 url。
link.absUrl("href") −在根据文档的基本 URI 进行解析后,提供绝对 URL。
描述
Element 对象表示一个 dom 元素,并提供方法来获取 html 页面中存在的相对和绝对 URL。
示例
使用您选择的任何编辑器在 C:/> jsoup 中创建以下 java 程序。
JsoupTester.java
import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class JsoupTester { public static void main(String[] args) throws IOException { String url = "http://www.tutorialspoint.com/"; Document document = Jsoup.connect(url).get(); Element link = document.select("a").first(); System.out.println("Relative Link: " + link.attr("href")); System.out.println("Absolute Link: " + link.attr("abs:href")); System.out.println("Absolute Link: " + link.absUrl("href")); } }
验证结果
使用 javac 编译器编译该类,如下所示:
C:\jsoup>javac JsoupTester.java
现在运行 JsoupTester 以查看结果。
C:\jsoup>java JsoupTester
查看结果。
Relative Link: index.htm Absolute Link: https://www.tutorialspoint.com/index.htm Absolute Link: https://www.tutorialspoint.com/index.htm