http://www.open-open.com/jsoup/parsing-a-document.htm
解析和遍曆一個HTML文檔
如何解析一個HTML文檔:
String html = "<html><head><title>First parse</title></head>" + "<body><p>Parsed HTML into a doc.</p></body></html>";Document doc = Jsoup.parse(html);
(更詳細內容可查看 解析一個HTML字串.)
其解析器能夠盡最大可能從你提供的HTML文檔來創見一個乾淨的解析結果,無論HTML的格式是否完整。比如它可以處理: 沒有關閉的標籤 (比如: <p>Lorem <p>Ipsum parses to <p>Lorem</p> <p>Ipsum</p>) 隱式標籤 (比如. 它可以自動將 <td>Table data</td>封裝成<table><tr><td>?) 建立可靠的文檔結構(html標籤包含head 和 body,在head只出現恰當的元素) 一個文檔的物件模型 文檔由多個Elements和TextNodes組成 (以及其它輔助nodes:詳細可查看:nodes package tree). 其繼承結構如下:Document繼承Element繼承Node. TextNode繼承 Node. 一個Element包含一個子節點集合,並擁有一個父Element。他們還提供了一個唯一的子項目過濾列表。
參見 資料幫浦:DOM遍曆 資料幫浦:Selector syntax
從一個URL載入一個Document 存在問題
你需要從一個網站擷取和解析一個HTML文檔,並尋找其中的相關資料。你可以使用下面解決方案: 解決方案
使用 Jsoup.connect(String url)方法:
Document doc = Jsoup.connect("http://example.com/").get();String title = doc.title();
說明
connect(String url) 方法建立一個新的 Connection, 和 get() 取得和解析一個HTML檔案。如果從該URL擷取HTML時發生錯誤,便會拋出 IOException,應適當處理。
Connection 介面還提供一個方法鏈來解決特殊請求,具體如下:
Document doc = Jsoup.connect("http://example.com") .data("query", "Java") .userAgent("Mozilla") .cookie("auth", "token") .timeout(3000) .post();
這個方法只支援Web URLs (http和https 協議); 假如你需要從一個檔案載入,可以使用parse(File in, String charsetName) 代替。
從一個檔案載入一個文檔 問題
在本機硬碟上有一個HTML檔案,需要對它進行解析從中抽取資料或進行修改。 辦法
可以使用靜態 Jsoup.parse(File in, String charsetName, String baseUri) 方法:
File input = new File("/tmp/input.html");Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
說明
parse(File in, String charsetName, String baseUri) 這個方法用來載入和解析一個HTML檔案。如在負載檔案的時候發生錯誤,將拋出IOException,應作適當處理。
baseUri 參數用於解決檔案中URLs是相對路徑的問題。如果不需要可以傳入一個空的字串。
另外還有一個方法parse(File in, String charsetName) ,它使用檔案的路徑做為 baseUri。 這個方法適用於如果被解析檔案位於網站的本地檔案系統,且相關連結也指向該檔案系統。
使用DOM方法來遍曆一個文檔 問題
你有一個HTML文檔要從中提取資料,並瞭解這個HTML文檔的結構。 方法
將HTML解析成一個Document之後,就可以使用類似於DOM的方法進行操作。範例程式碼:
File input = new File("/tmp/input.html");Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");Element content = doc.getElementById("content");Elements links = content.getElementsByTag("a");for (Element link : links) { String linkHref = link.attr("href"); String linkText = link.text();}
說明
Elements這個對象提供了一系列類似於DOM的方法來尋找元素,抽取並處理其中的資料。具體如下: 尋找元素 getElementById(String id) getElementsByTag(String tag) getElementsByClass(String className) getElementsByAttribute(String key) (and related methods) Element siblings: siblingElements(), firstElementSibling(), lastElementSibling();nextElementSibling(), previousElementSibling() Graph: parent(), children(), child(int index) 元素資料 attr(String key)擷取屬性attr(String key, String value)設定屬性 attributes()擷取所有屬性 id(), className() and classNames() text()擷取常值內容text(String value) 設定常值內容 html()擷取元素內HTMLhtml(String value)設定元素內的HTML內容 outerHtml()擷取元素外HTML內容 data()擷取資料內容(例如:script和style標籤) tag() and tagName() 操作HTML和文本 append(String html), prepend(String html)