Jsoup 获取属性

以下示例将展示在将 HTML 字符串解析为 Document 对象后获取 dom 元素属性的方法的使用。

Jsoup 获取属性 语法

Document document = Jsoup.parse(html);
Element link = document.select("a").first();
System.out.println("Href: " + link.attr("href"));
  • document : 文档对象代表 HTML DOM。

  • Jsoup : 解析给定 HTML 字符串的主类。

  • html : HTML 字符串。

  • link : 元素对象表示表示锚标记的 html 节点元素。

  • link.attr() : attr(attribute) 方法检索元素属性。

Jsoup 获取属性 说明

Element对象代表一个dom元素,并提供了多种获取dom元素属性的方法。

Jsoup 获取属性 示例

package com.yiidian;

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.yiidian.com'>一点教程网</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"));
   }
}

输出结果为:

热门文章

优秀文章