以下示例将HTML解析为Document对象后,使用Elements方法来获取dom元素的属性。

Document document=Jsoup.parse(html);
Element link=document.select("a").first();
System.out.println("Href: " + link.attr("href"));

元素对象代表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=''>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

参考链接

https://www.learnfk.com/jsoup/jsoup-extract-attribute.html