Jsoup-extract-attribute

提供:Dev Guides
移動先:案内検索

jsoup-属性の抽出

次の例では、HTML文字列をDocumentオブジェクトに解析した後、dom要素の属性を取得するメソッドの使用方法を示します。

構文

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)メソッドは、要素の属性を取得します。

説明

要素オブジェクトは、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