jsoup - 提取属性
以下示例将展示如何使用方法将 HTML 字符串解析为 Document 对象后获取 dom 元素的属性。
语法
Document document = Jsoup.parse(html); Element link = document.select("a").first(); System.out.println("Href: " + link.attr("href"));
其中
document − document 对象代表 HTML DOM。
Jsoup − 主类用于解析给定的 HTML 字符串。
html − HTML 字符串。
link − Element 对象表示表示锚标记的 html 节点元素。
link.attr() − attr(attribute) 方法检索元素属性。
描述
Element 对象表示 dom 元素,并提供各种方法来获取 dom 元素的属性。
示例
使用您选择的任何编辑器在 C:/> jsoup 中创建以下 java 程序。
JsoupTester.java
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class JsoupTester { public static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body>" + "<p>Sample Content</p>" + "<div id='sampleDiv'><a href='www.google.com'>Google</a>" + "<h3><a>Sample</a><h3>" +"</div>" +"</body></html>"; Document document = Jsoup.parse(html); //a with href Element link = document.select("a").first(); System.out.println("Href: " + link.attr("href")); } }
验证结果
使用 javac 编译器编译该类,如下所示:
C:\jsoup>javac JsoupTester.java
现在运行 JsoupTester 以查看结果。
C:\jsoup>java JsoupTester
查看结果。
Href: www.google.com