jsoup - 提取 HTML



以下示例將展示將 HTML 字串解析到文件物件後,如何使用方法來獲取內部 html 和外部 html。

語法

Document document = Jsoup.parse(html);
Element link = document.select("a").first();         

System.out.println("Outer HTML: " + link.outerHtml());
System.out.println("Inner HTML: " + link.html());

其中

  • document - 文件物件表示 HTML DOM。

  • Jsoup - 用於解析給定 HTML 字串的主類。

  • html - HTML 字串。

  • link - 元素物件表示表示錨點標籤的 html 節點元素。

  • link.outerHtml() - outerHtml() 方法檢索元素的完整 html。

  • link.html() - html() 方法檢索元素的內部 html。

描述

元素物件表示一個 dom 元素並提供各種方法來獲取 dom 元素的 html。

示例

在 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("Outer HTML: " + link.outerHtml());
      System.out.println("Inner HTML: " + link.html());
   }
}

驗證結果

使用 javac 編譯器編譯類,如下所示

C:\jsoup>javac JsoupTester.java

現在執行 JsoupTester 檢視結果。

C:\jsoup>java JsoupTester

檢視結果。

Outer HTML: <a href="www.google.com">Google</a>
Inner HTML: Google
廣告
© . All rights reserved.