1. 程式人生 > >如何將字符串轉化為Jsoup的Document 對象

如何將字符串轉化為Jsoup的Document 對象

des ng- 轉化 main 解析html ont document gin wid

有些時候在java操作解析html元素的時候比較繁瑣,今天螃蟹就介紹一種可將html轉換為document對象的方法——jsoup

jsoup為我們解析html提供了比較全的API接口,我們通過將html轉換為document對象後,在java中便可以形同寫html標簽一般進行元素的解析、屬性的獲取。

首先看一個例子:

String html="<html><header></header><body>

<div>hello world</div>

</body><html/>";


這是提供的html文本,在轉換成document對象後,我們要獲取a鏈接的地址及文本:
代碼如下:


    1. /**
    2. * 文件名:Chapter1.java
    3. *
    4. * 日期:2015年7月12日
    5. *
    6. */

    7. import org.jsoup.Jsoup;
    8. import org.jsoup.nodes.Document;
    9. import org.jsoup.nodes.Element;
    10. import org.jsoup.select.Elements;
    11. /**
    12. *
    13. *
    14. *
    15. *
    16. *
    17. * @version: 2015年7月12日 下午4:55:41
    18. */
    19. public class Chapter1 {
    20. /**
    21. * @author: IT學習者
    22. *
    23. *
    24. * @version: 2015年7月12日 下午4:55:42
    25. */
    26. public static void main(String[] args) {
    27. String html = "<html><head><title>IT學習者</title></head>"
    28. + "<body><div id=\"content\">"
    29. + "<a href=‘> IT學習者官網 </a>"
    30. + "<a href=‘‘> IT學習者論壇 </a>"
    31. + "</div></body></html>";
    32. Document doc = Jsoup.parse(html);
    33. Element content = doc.getElementById("content");
    34. Elements links = content.getElementsByTag("a");
    35. for (Element link : links) {
    36. String linkHref = link.attr("href");
    37. String linkText = link.text();
    38. System.out.println("linkHref:" + linkHref);
    39. System.out.println("linkText:" + linkText);
    40. }
    41. }
    42. }

如何將字符串轉化為Jsoup的Document 對象