如何將字符串轉化為Jsoup的Document 對象
阿新 • • 發佈:2017-10-29
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鏈接的地址及文本:
代碼如下:
- /**
- * 文件名:Chapter1.java
- *
- * 日期:2015年7月12日
- *
- */
-
- import org.jsoup.Jsoup;
- import org.jsoup.nodes.Document;
- import org.jsoup.nodes.Element;
- import org.jsoup.select.Elements;
- /**
- *
-
*
- *
-
*
- *
- * @version: 2015年7月12日 下午4:55:41
- */
-
public class Chapter1 {
- /**
- * @author: IT學習者
-
*
- *
- * @version: 2015年7月12日 下午4:55:42
- */
- public static void main(String[] args) {
- String html = "<html><head><title>IT學習者</title></head>"
-
+ "<body><div id=\"content\">"
- + "<a href=‘> IT學習者官網 </a>"
- + "<a href=‘‘> IT學習者論壇 </a>"
- + "</div></body></html>";
- Document doc = Jsoup.parse(html);
- Element content = doc.getElementById("content");
- Elements links = content.getElementsByTag("a");
- for (Element link : links) {
- String linkHref = link.attr("href");
- String linkText = link.text();
- System.out.println("linkHref:" + linkHref);
- System.out.println("linkText:" + linkText);
- }
- }
- }
如何將字符串轉化為Jsoup的Document 對象