jsoup 簡介
Java 程序在解析 HTML 文檔時,相信你們都接觸過 htmlparser 這個開源項目,我曾經在 IBM DW 上發表過兩篇關於 htmlparser 的文章,分別是:從 HTML 中攫取你所需的信息和 擴展 HTMLParser 對自定義標籤的處理能力。但如今我已經再也不使用 htmlparser 了,緣由是 htmlparser 不多更新,但最重要的是有了 jsoup 。
jsoup 是一款 Java 的 HTML 解析器,可直接解析某個 URL 地址、HTML 文本內容。它提供了一套很是省力的 API,可經過 DOM,CSS 以及相似於 jQuery 的操做方法來取出和操做數據。
jsoup 的主要功能以下:
1. 從一個 URL,文件或字符串中解析 HTML;
2. 使用 DOM 或 CSS 選擇器來查找、取出數據;
3. 可操做 HTML 元素、屬性、文本;php
官網地址:http://www.open-open.com/jsoup/ css
jsoup Cookbook(中文版)
入門
1.解析和遍歷一個html文檔
輸入
2.解析一個html字符串
3.解析一個body片段
4.根據一個url加載Document對象
5.根據一個文件加載Document對象
數據抽取
6.使用dom方法來遍歷一個Document對象
7.使用選擇器語法來查找元素
8.從元素集合抽取屬性、文本和html內容
9.URL處理
10.程序示例:獲取全部連接
數據修改
11.設置屬性值
12.設置元素的html內容
13.設置元素的文本內容
html清理
14.消除不受信任的html (來防止xss攻擊)html
1.解析和遍歷一個HTML文檔
如何解析一個HTML文檔:java
1
2
3
|
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字符串.)node
其解析器可以盡最大可能從你提供的HTML文檔來創見一個乾淨的解析結果,不管HTML的格式是否完整。好比它能夠處理:jquery
沒有關閉的標籤 (好比: <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 syntaxcss3
2.解析一個HTML字符串
存在問題
來自用戶輸入,一個文件或一個網站的HTML字符串,你可能須要對它進行解析並取其內容,或校驗其格式是否完整,或想修改它。怎麼辦?jsonu可以幫你輕鬆解決這些問題web
解決方法
使用靜態Jsoup.parse(String html) 方法或 Jsoup.parse(String html, String baseUri)示例代碼:正則表達式
1
2
3
|
String html =
"<html><head><title>First parse</title></head>"
+
"<body><p>Parsed HTML into a doc.</p></body></html>"
;
Document doc = Jsoup.parse(html);
|
描述django
parse(String html, String baseUri) 這方法可以將輸入的HTML解析爲一個新的文檔 (Document),參數 baseUri 是用來將相對 URL 轉成絕對URL,並指定從哪一個網站獲取文檔。如這個方法不適用,你可使用 parse(String html) 方法來解析成HTML字符串如上面的示例。.
只要解析的不是空字符串,就能返回一個結構合理的文檔,其中包含(至少) 一個head和一個body元素。
一旦擁有了一個Document,你就可使用Document中適當的方法或它父類 Element和Node中的方法來取得相關數據。
3.解析一個body片段
問題
假如你有一個HTML片段 (好比. 一個 div 包含一對 p 標籤; 一個不完整的HTML文檔) 想對它進行解析。這個HTML片段能夠是用戶提交的一條評論或在一個CMS頁面中編輯body部分。
辦法
使用Jsoup.parseBodyFragment(String html)方法.
1
2
3
|
String html =
"<div><p>Lorem ipsum.</p>"
;
Document doc = Jsoup.parseBodyFragment(html);
Element body = doc.body();
|
說明
parseBodyFragment 方法建立一個空殼的文檔,並插入解析過的HTML到body元素中。假如你使用正常的Jsoup.parse(String html) 方法,一般你也能夠獲得相同的結果,可是明確將用戶輸入做爲 body片斷處理,以確保用戶所提供的任何糟糕的HTML都將被解析成body元素。
Document.body() 方法可以取得文檔body元素的全部子元素,與 doc.getElementsByTag("body")相同。
保證安全Stay safe
假如你可讓用戶輸入HTML內容,那麼要當心避免跨站腳本攻擊。利用基於 Whitelist 的清除器和 clean(String bodyHtml, Whitelist whitelist)方法來清除用戶輸入的惡意內容。
4.從一個URL加載一個Document
你須要從一個網站獲取和解析一個HTML文檔,並查找其中的相關數據。你可使用下面解決方法:
使用 Jsoup.connect(String url)
方法:
1
2
|
Document doc = Jsoup.connect(
"http://example.com/"
).get();
String title = doc.title();
|
說明
connect(String url)
方法建立一個新的 Connection
, 和 get()
取得和解析一個HTML文件。若是從該URL獲取HTML時發生錯誤,便會拋出 IOException,應適當處理。
Connection
接口還提供一個方法鏈來解決特殊請求,具體以下:
1
2
3
4
5
6
|
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)
代替。
5.從一個文件加載一個文檔
在本機硬盤上有一個HTML文件,須要對它進行解析從中抽取數據或進行修改。
可使用靜態 Jsoup.parse(File in, String charsetName, String baseUri)
方法:
1
2
|
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
。 這個方法適用於若是被解析文件位於網站的本地文件系統,且相關連接也指向該文件系統。
6.使用DOM方法來遍歷一個文檔
你有一個HTML文檔要從中提取數據,並瞭解這個HTML文檔的結構。
將HTML解析成一個Document
以後,就可使用相似於DOM的方法進行操做。示例代碼:
1
2
3
4
5
6
7
8
9
|
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)siblingElements()
, firstElementSibling()
, lastElementSibling()
;nextElementSibling()
, previousElementSibling()
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()
append(String html)
, prepend(String html)
appendText(String text)
, prependText(String text)
appendElement(String tagName)
, prependElement(String tagName)
html(String value)
你想使用相似於CSS或jQuery的語法來查找和操做元素。
可使用Element.select(String selector)
和 Elements.select(String selector)
方法實現:
1
2
3
4
5
6
7
8
9
10
11
|
File input =
new
File(
"/tmp/input.html"
);
Document doc = Jsoup.parse(input,
"UTF-8"
,
"http://example.com/"
);
Elements links = doc.select(
"a[href]"
);
//帶有href屬性的a元素
Elements pngs = doc.select(
"img[src$=.png]"
);
//擴展名爲.png的圖片
Element masthead = doc.select(
"div.masthead"
).first();
//class等於masthead的div標籤
Elements resultLinks = doc.select(
"h3.r > a"
);
//在h3元素以後的a元素
|
說明
jsoup elements對象支持相似於CSS (或jquery)的選擇器語法,來實現很是強大和靈活的查找功能。.
這個select
方法在Document
, Element
,或Elements
對象中均可以使用。且是上下文相關的,所以可實現指定元素的過濾,或者鏈式選擇訪問。
Select方法將返回一個Elements
集合,並提供一組方法來抽取和處理結果。
tagname
: 經過標籤查找元素,好比:a
ns|tag
: 經過標籤在命名空間查找元素,好比:能夠用 fb|name
語法來查找 <fb:name>
元素#id
: 經過ID查找元素,好比:#logo
.class
: 經過class名稱查找元素,好比:.masthead
[attribute]
: 利用屬性查找元素,好比:[href]
[^attr]
: 利用屬性名前綴來查找元素,好比:能夠用[^data-]
來查找帶有HTML5 Dataset屬性的元素[attr=value]
: 利用屬性值來查找元素,好比:[width=500]
[attr^=value]
, [attr$=value]
, [attr*=value]
: 利用匹配屬性值開頭、結尾或包含屬性值來查找元素,好比:[href*=/path/]
[attr~=regex]
: 利用屬性值匹配正則表達式來查找元素,好比: img[src~=(?i)\.(png|jpe?g)]
*
: 這個符號將匹配全部元素el#id
: 元素+ID,好比: div#logo
el.class
: 元素+class,好比: div.masthead
el[attr]
: 元素+class,好比: a[href]
a[href].highlight
ancestor child
: 查找某個元素下子元素,好比:能夠用.body p
查找在"body"元素下的全部 p
元素parent > child
: 查找某個父元素下的直接子元素,好比:能夠用div.content > p
查找 p
元素,也能夠用body > *
查找body標籤下全部直接子元素siblingA + siblingB
: 查找在A元素以前第一個同級元素B,好比:div.head + div
siblingA ~ siblingX
: 查找A元素以前的同級X元素,好比:h1 ~ p
el, el, el
:多個選擇器組合,查找匹配任一選擇器的惟一元素,例如:div.masthead, div.logo
:lt(n)
: 查找哪些元素的同級索引值(它的位置在DOM樹中是相對於它的父節點)小於n,好比:td:lt(3)
表示小於三列的元素:gt(n)
:查找哪些元素的同級索引值大於n
,好比
: div p:gt(2)
表示哪些div中有包含2個以上的p元素:eq(n)
: 查找哪些元素的同級索引值與n
相等,好比:form input:eq(1)
表示包含一個input標籤的Form元素:has(seletor)
: 查找匹配選擇器包含元素的元素,好比:div:has(p)
表示哪些div包含了p元素:not(selector)
: 查找與選擇器不匹配的元素,好比: div:not(.logo)
表示不包含 class="logo" 元素的全部 div 列表:contains(text)
: 查找包含給定文本的元素,搜索不區分大不寫,好比: p:contains(jsoup)
:containsOwn(text)
: 查找直接包含給定文本的元素:matches(regex)
: 查找哪些元素的文本匹配指定的正則表達式,好比:div:matches((?i)login)
:matchesOwn(regex)
: 查找自身包含文本匹配指定正則表達式的元素能夠查看Selector
API參考來了解更詳細的內容
在解析得到一個Document實例對象,並查找到一些元素以後,你但願取得在這些元素中的數據。
Node.attr(String key)
方法Element.text()
方法Element.html()
, 或 Node.outerHtml()
方法示例:
1
2
3
4
5
6
7
8
9
10
11
|
String html =
"<p>An <a href='http://example.com/'><b>example</b></a> link.</p>"
;
Document doc = Jsoup.parse(html);
//解析HTML字符串返回一個Document實現
Element link = doc.select(
"a"
).first();
//查找第一個a元素
String text = doc.body().text();
// "An example link"//取得字符串中的文本
String linkHref = link.attr(
"href"
);
// "http://example.com/"//取得連接地址
String linkText = link.text();
// "example""//取得連接地址中的文本
String linkOuterH = link.outerHtml();
// "<a href="http://example.com"><b>example</b></a>"
String linkInnerH = link.html();
// "<b>example</b>"//取得連接內的html內容
|
說明
上述方法是元素數據訪問的核心辦法。此外還其它一些方法可使用:
這些訪問器方法都有相應的setter方法來更改數據.
Element
和Elements
集合類的參考文檔你有一個包含相對URLs路徑的HTML文檔,須要將這些相對路徑轉換成絕對路徑的URLs。
base URI
,而後abs:
屬性前綴來取得包含base URI
的絕對路徑。代碼以下:
1
2
3
4
5
|
Document doc = Jsoup.connect(
"http://www.open-open.com"
).get();
Element link = doc.select(
"a"
).first();
String relHref = link.attr(
"href"
);
// == "/"
String absHref = link.attr(
"abs:href"
);
// "http://www.open-open.com/"
|
說明
在HTML元素中,URLs常常寫成相對於文檔位置的相對路徑: <a href="/download">...</a>
. 當你使用 Node.attr(String key)
方法來取得a元素的href屬性時,它將直接返回在HTML源碼中指定定的值。
假如你須要取得一個絕對路徑,須要在屬性名前加 abs:
前綴。這樣就能夠返回包含根路徑的URL地址attr("abs:href")
所以,在解析HTML文檔時,定義base URI很是重要。
若是你不想使用abs:
前綴,還有一個方法可以實現一樣的功能 Node.absUrl(String key)
。
這個示例程序將展現如何從一個URL得到一個頁面。而後提取頁面中的全部連接、圖片和其它輔助內容。並檢查URLs和文本信息。
運行下面程序須要指定一個URLs做爲參數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
import
org.jsoup.Jsoup;
import
org.jsoup.helper.Validate;
import
org.jsoup.nodes.Document;
import
org.jsoup.nodes.Element;
import
org.jsoup.select.Elements;
import
java.io.IOException;
/**
* Example program to list links from a URL.
*/
public
class
ListLinks {
public
static
void
main(String[] args)
throws
IOException {
// Validate.isTrue(args.length == 1, "usage: supply url to fetch");
String url =
"http://news.ycombinator.com/"
;
print(
"Fetching %s..."
, url);
Document doc = Jsoup.connect(url).get();
Elements links = doc.select(
"a[href]"
);
//"a[href]" //帶有href屬性的a元素
Elements media = doc.select(
"[src]"
);
//利用屬性查找元素,好比:[href]
Elements imports = doc.select(
"link[href]"
);
print(
"\nMedia: (%d)"
, media.size());
for
(Element src : media) {
if
(src.tagName().equals(
"img"
))
print(
" * %s: <%s> %sx%s (%s)"
,
src.tagName(), src.attr(
"abs:src"
), src.attr(
"width"
), src.attr(
"height"
),
trim(src.attr(
"alt"
),
20
));
//src.attr("src")結果:<y18.gif> 18x18 ()
//src.attr("abs:src")結果:<https://news.ycombinator.com/y18.gif> 18x18 ()
else
print(
" * %s: <%s>"
, src.tagName(), src.attr(
"abs:src"
));
}
print(
"\nImports: (%d)"
, imports.size());
for
(Element link : imports) {
print(
" * %s <%s> (%s)"
, link.tagName(),link.attr(
"abs:href"
), link.attr(
"rel"
));
}
print(
"\nLinks: (%d)"
, links.size());
for
(Element link : links) {
print(
" * a: <%s> (%s)"
, link.attr(
"abs:href"
), trim(link.text(),
35
));
}
}
private
static
void
print(String msg, Object... args) {
System.out.println(String.format(msg, args));
}
private
static
String trim(String s,
int
width) {
if
(s.length() > width)
return
s.substring(
0
, width-
1
) +
"."
;
else
return
s;
}
}
//org/jsoup/examples/ListLinks.java
|
示例輸入結果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
Fetching http:
//news.ycombinator.com/...
Media: (
38
)
* img: <http:
//ycombinator.com/images/y18.gif> 18x18 ()
* img: <http:
//ycombinator.com/images/s.gif> 10x1 ()
* img: <http:
//ycombinator.com/images/grayarrow.gif> x ()
* img: <http:
//ycombinator.com/images/s.gif> 0x10 ()
* script: <http:
//www.co2stats.com/propres.php?s=1138>
* img: <http:
//ycombinator.com/images/s.gif> 15x1 ()
* img: <http:
//ycombinator.com/images/hnsearch.png> x ()
* img: <http:
//ycombinator.com/images/s.gif> 25x1 ()
* img: <http:
//mixpanel.com/site_media/images/mixpanel_partner_logo_borderless.gif> x (Analytics by Mixpan.)
Imports: (
2
)
* link <http:
//ycombinator.com/news.css> (stylesheet)
* link <http:
//ycombinator.com/favicon.ico> (shortcut icon)
Links: (
141
)
* a: <http:
//ycombinator.com> ()
* a: <http:
//news.ycombinator.com/news> (Hacker News)
* a: <http:
//news.ycombinator.com/newest> (new)
* a: <http:
//news.ycombinator.com/newcomments> (comments)
* a: <http:
//news.ycombinator.com/leaders> (leaders)
* a: <http:
//news.ycombinator.com/jobs> (jobs)
* a: <http:
//news.ycombinator.com/submit> (submit)
* a: <http:
//news.ycombinator.com/x?fnid=JKhQjfU7gW> (login)
* a: <http:
//news.ycombinator.com/vote?for=1094578&dir=up&whence=%6e%65%77%73> ()
* a: <http:
//www.readwriteweb.com/archives/facebook_gets_faster_debuts_homegrown_php_compiler.php?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+readwriteweb+%28ReadWriteWeb%29&utm_content=Twitter> (Facebook speeds up PHP)
* a: <http:
//news.ycombinator.com/user?id=mcxx> (mcxx)
* a: <http:
//news.ycombinator.com/item?id=1094578> (9 comments)
* a: <http:
//news.ycombinator.com/vote?for=1094649&dir=up&whence=%6e%65%77%73> ()
* a: <http:
//groups.google.com/group/django-developers/msg/a65fbbc8effcd914> ("Tough. Django produces XHTML.")
* a: <http:
//news.ycombinator.com/user?id=andybak> (andybak)
* a: <http:
//news.ycombinator.com/item?id=1094649> (3 comments)
* a: <http:
//news.ycombinator.com/vote?for=1093927&dir=up&whence=%6e%65%77%73> ()
* a: <http:
//news.ycombinator.com/x?fnid=p2sdPLE7Ce> (More)
* a: <http:
//news.ycombinator.com/lists> (Lists)
* a: <http:
//news.ycombinator.com/rss> (RSS)
* a: <http:
//ycombinator.com/bookmarklet.html> (Bookmarklet)
* a: <http:
//ycombinator.com/newsguidelines.html> (Guidelines)
* a: <http:
//ycombinator.com/newsfaq.html> (FAQ)
* a: <http:
//ycombinator.com/newsnews.html> (News News)
* a: <http:
//news.ycombinator.com/item?id=363> (Feature Requests)
* a: <http:
//ycombinator.com> (Y Combinator)
* a: <http:
//ycombinator.com/w2010.html> (Apply)
* a: <http:
//ycombinator.com/lib.html> (Library)
* a: <http:
//www.webmynd.com/html/hackernews.html> ()
* a: <http:
//mixpanel.com/?from=yc> ()
|
在你解析一個Document以後可能想修改其中的某些屬性值,而後再保存到磁盤或都輸出到前臺頁面。
可使用屬性設置方法 Element.attr(String key, String value)
, 和 Elements.attr(String key, String value)
.
假如你須要修改一個元素的 class
屬性,可使用 Element.addClass(String className)
和Element.removeClass(String className)
方法。
Elements
提供了批量操做元素屬性和class的方法,好比:要爲div中的每個a元素都添加一個rel="nofollow"
可使用以下方法:
1
|
doc.select(
"div.comments a"
).attr(
"rel"
,
"nofollow"
);
|
說明
與Element
中的其它方法同樣,attr
方法也是返回當 Element
(或在使用選擇器是返回 Elements
集合)。這樣可以很方便使用方法連用的書寫方式。好比:
1
|
doc.select(
"div.masthead"
).attr(
"title"
,
"jsoup"
).addClass(
"round-box"
);
|
你須要一個元素中的HTML內容
可使用Element
中的HTML設置方法具體以下:
1
2
3
4
5
6
7
8
9
|
Element div = doc.select(
"div"
).first();
// <div></div>
div.html(
"<p>lorem ipsum</p>"
);
// <div><p>lorem ipsum</p></div>
div.prepend(
"<p>First</p>"
);
//在div前添加html內容
div.append(
"<p>Last</p>"
);
//在div以後添加html內容
// 添完後的結果: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>
Element span = doc.select(
"span"
).first();
// <span>One</span>
span.wrap(
"<li><a href='http://example.com/'></a></li>"
);
// 添完後的結果: <li><a href="http://example.com"><span>One</span></a></li>
|
說明
Element.html(String html)
這個方法將先清除元素中的HTML內容,而後用傳入的HTML代替。Element.prepend(String first)
和 Element.append(String last)
方法用於在分別在元素內部HTML的前面和後面添加HTML內容Element.wrap(String around)
對元素包裹一個外部HTML內容。能夠查看API參考文檔中 Element.prependElement(String tag)
和Element.appendElement(String tag)
方法來建立新的元素並做爲文檔的子元素插入其中。
你須要修改一個HTML文檔中的文本內容
可使用Element
的設置方法::
1
2
3
4
5
|
Element div = doc.select(
"div"
).first();
// <div></div>
div.text(
"five > four"
);
// <div>five > four</div>
div.prepend(
"First "
);
div.append(
" Last"
);
// now: <div>First five > four Last</div>
|
說明
文本設置方法與 HTML setter 方法同樣:
Element.text(String text)
將清除一個元素中的內部HTML內容,而後提供的文本進行代替Element.prepend(String first)
和 Element.append(String last)
將分別在元素的內部html先後添加文本節點。對於傳入的文本若是含有像 <
, >
等這樣的字符,將以文本處理,而非HTML。
在作網站的時候,常常會提供用戶評論的功能。有些不懷好意的用戶,會搞一些腳本到評論內容中,而這些腳本可能會破壞整個頁面的行爲,更嚴重的是獲取一些機要信息,此時須要清理該HTML,以免跨站腳本cross-site scripting攻擊(XSS)。
使用jsoup HTML Cleaner
方法進行清除,但須要指定一個可配置的 Whitelist
。
1
2
3
4
|
String unsafe =
"<p><a href='http://example.com/' onclick='stealCookies()'>Link</a></p>"
;
String safe = Jsoup.clean(unsafe, Whitelist.basic());
// now: <p><a href="http://example.com/" rel="nofollow">Link</a></p>
|
說明
XSS又叫CSS (Cross Site Script) ,跨站腳本攻擊。它指的是惡意攻擊者往Web頁面裏插入惡意html代碼,當用戶瀏覽該頁之時,嵌入其中Web裏面的html代碼會被執行,從而達到惡意攻擊用戶的特殊目的。XSS屬於被動式的攻擊,由於其被動且很差利用,因此許多人常忽略其危害性。因此咱們常常只讓用戶輸入純文本的內容,但這樣用戶體驗就比較差了。
一個更好的解決方法就是使用一個富文本編輯器WYSIWYG如CKEditor 和 TinyMCE。這些能夠輸出HTML並可以讓用戶可視化編輯。雖然他們能夠在客戶端進行校驗,可是這樣還不夠安全,須要在服務器端進行校驗並清除有害的HTML代碼,這樣才能確保輸入到你網站的HTML是安全的。不然,攻擊者可以繞過客戶端的Javascript驗證,並注入不安全的HMTL直接進入您的網站。
jsoup的whitelist清理器可以在服務器端對用戶輸入的HTML進行過濾,只輸出一些安全的標籤和屬性。
jsoup提供了一系列的Whitelist
基本配置,可以知足大多數要求;但若有必要,也能夠進行修改,不過要當心。
這個cleaner很是好用不只能夠避免XSS攻擊,還能夠限制用戶能夠輸入的標籤範圍。
Cleaner
,瞭解如何返回一個 Document
對象,而不是字符串Whitelist
,瞭解如何建立一個自定義的whitelist
轉發請註明出處:http://www.cnblogs.com/jycboy/p/jsoupdoc.html