# 解析一個body片斷
<div><h2>問題</h2>
<p>假如你有一個HTML片斷 (比如. 一個 <code>div</code> 包含一對 <code>p</code> 標簽; 一個不完整的HTML文檔) 想對它進行解析。這個HTML片斷可以是用戶提交的一條評論或在一個CMS頁面中編輯body部分。</p>
<h2>辦法</h2>
<p>使用<code><a title="Parse a fragment of HTML, with the assumption that it forms the body of the HTML." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#parseBodyFragment%28java.lang.String%29">Jsoup.parseBodyFragment(String
html)</a></code>方法.</p>
<pre><code>String html = "<div><p>Lorem ipsum.</p>";
Document doc = Jsoup.parseBodyFragment(html);
Element body = doc.body();
</code></pre>
<h2>說明</h2>
<p><code>parseBodyFragment</code> 方法創建一個空殼的文檔,并插入解析過的HTML到<code>body</code>元素中。假如你使用正常的 <code><a title="Parse HTML into a Document." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#parse%28java.lang.String%29">Jsoup.parse(String
html)</a></code> 方法,通常你也可以得到相同的結果,但是明確將用戶輸入作為 body片段處理,以確保用戶所提供的任何糟糕的HTML都將被解析成body元素。</p>
<p><code><a title="Accessor to the document's body element." href="http://jsoup.org/apidocs/org/jsoup/nodes/Document.html#body%28%29">Document.body()</a></code>
方法能夠取得文檔body元素的所有子元素,與 <code>doc.getElementsByTag("body")</code>相同。</p>
<h2>保證安全Stay safe</h2>
<p>假如你可以讓用戶輸入HTML內容,那么要小心避免跨站腳本攻擊。利用基于 <code><a title="Whitelists define what HTML (elements and attributes) to allow through the cleaner." href="http://jsoup.org/apidocs/org/jsoup/safety/Whitelist.html">Whitelist</a></code>
的清除器和 <code><a title="Get safe HTML from untrusted input HTML, by parsing input HTML and filtering it through a white-list of permitted tags and attributes." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#clean%28java.lang.String,%20org.jsoup.safety.Whitelist%29">clean(String
bodyHtml, Whitelist whitelist)</a></code>方法來清除用戶輸入的惡意內容。</p><br></div>
- Introduction
- 爬蟲相關技能介紹
- 爬蟲簡單介紹
- 爬蟲涉及到的知識點
- 爬蟲用途
- 爬蟲流程介紹
- 需求描述
- Http請求處理
- http基礎知識介紹
- http狀態碼
- httpheader
- java原生態處理http
- URL類
- 獲取URL請求狀態
- 模擬Http請求
- apache httpclient
- Httpclient1
- httpclient2
- httpclient3
- httpclient4
- httpclient5
- httpclient6
- okhttp
- OKhttp使用教程
- 技術使用
- java執行javascript
- 網頁解析
- Xpath介紹
- HtmlCleaner
- HtmlCleaner介紹
- HtmlCleaner使用
- HtmlParser
- HtmlParser介紹
- Jsoup
- 解析和遍歷一個HTML文檔
- 解析一個HTML字符串
- 解析一個body片斷
- 從一個URL加載一個Document
- 從一個文件加載一個文檔
- 使用DOM方法來遍歷一個文檔
- 使用選擇器語法來查找元素
- 從元素抽取屬性,文本和HTML
- 處理URLs
- 示例程序 獲取所有鏈接
- 設置屬性的值
- 設置一個元素的HTML內容
- 消除不受信任的HTML (來防止XSS攻擊)
- 正則表達式
- elasticsearch筆記
- 下載安裝elasticsearch
- 檢查es服務健康