jsoup學習總結

 

轉載自:http://blog.csdn.net/u010814849/article/details/52526582

Jsoup學習總結

摘要

Jsoup是一款比較好的Java版HTML解析器。可直接解析某個URL地址、HTML文本內容。它提供了一套非常省力的API,可通過DOM,CSS以及類似於jQuery的操作方法來取出和操作數據。

jSOUP主要功能

  1. 從一個URL,文件或字符串中解析HTML;
  2. 使用DOM或CSS選擇器來查找、取出數據;
  3. 可操作HTML元素、屬性、文本

環境搭建

MAVEN依賴


 
  1. <dependency>
  2. <groupId>org.jsoup</groupId>
  3. <artifactId>jsoup</artifactId>
  4. <version>1.8.3</version>
  5. </dependency>

1. 輸入

jsoup 可以從包括字符串、URL地址以及本地文件來加載HTML 文檔,並生成Document對象實例。

  • Document對象(一個文檔的對象模型):文檔由多個Elements和TextNodes組成 (以及其它輔助nodes:詳細可查看:nodes package tree). 
    其繼承結構如下:Document繼承Element繼承NodeTextNode繼承 Node.

  • 一個Element包含一個子節點集合,並擁有一個父Element。他們還提供了一個唯一的子元素過濾列表。

1.1 從字符串中輸入HTML文檔

1.1.1 解析一個html字符串

使用靜態方法Jsoup.parse(String html) 或 Jsoup.parse(String html, String baseUri)


 
  1. String html = "<html><head><title>開源中國社區</title></head>"
  2. +"<body><p>這裏是jsoup 項目的相關文章</p></body></html>";
  3. Document doc = Jsoup.parse(html);

說明:

  1. 其解析器能夠盡最大可能從你提供的HTML文檔來創見一個乾淨的解析結果,無論HTML的格式是否完整。比如它可以處理:

    • 沒有關閉的標籤 (比如: <p>Lorem <p>Ipsum 解析爲 <p>Lorem</p> <p>Ipsum</p>)
    • 隱式標籤 (比如:它可以自動將 <td>Table data</td>包裝成<table><tr><td>?)
    • 創建可靠的文檔結構(html標籤包含head 和 body,在head只出現恰當的元素)
  2. parse(String html, String baseUri) 這個方法能夠將輸入的HTML解析爲一個新的文檔 (Document),參數 baseUri 是用來將相對 URL 轉成絕對URL,並指定從哪個網站獲取文檔。如這個方法不適用,你可以使用 parse(String html) 方法來解析成HTML字符串如上面的示例。

  3. 只要解析的不是空字符串,就能返回一個結構合理的文檔,其中包含(至少) 一個head和一個body元素。

  4. 一旦擁有了一個Document,你就可以使用Document中適當的方法或它父類 Element 和 Node 中的方法來取得相關數據

1.1.2 解析一個body片斷

假如你有一個HTML片斷 (比如. 一個 div 包含一對 p 標籤; 一個不完整的HTML文檔) 想對它進行解析。這個HTML片斷可以是用戶提交的一條評論或在一個CMS頁面中編輯body部分。可以使用Jsoup.parseBodyFragment(String html) 方法.


 
  1. String html = "<div><p>Lorem ipsum.</p>";
  2. Document doc = Jsoup.parseBodyFragment(html);
  3. Element body = doc.body();

說明:

  1. parseBodyFragment 方法創建一個空殼的文檔,並插入解析過的HTML到body元素中。假如你使用正常的 Jsoup.parse(String html) 方法,通常你也可以得到相同的結果,但是明確將用戶輸入作爲 body片段處理,以確保用戶所提供的任何糟糕的HTML都將被解析成body元素。
  2. Document.body() 方法能夠取得文檔body元素的所有子元素,與 doc.getElementsByTag("body")相同。

1.2 從URL直接加載HTML文檔

從一個網站獲取和解析一個HTML文檔,並查找其中的相關數據,可以使用 Jsoup.connect(String url)方法。


 
  1. Document doc =Jsoup.connect("網址/").get();
  2. String title = doc.title();
  3. Document doc =Jsoup.connect("網址/")
  4. .data("query", "Java") //請求參數
  5. .userAgent("I’mjsoup") //設置User-Agent
  6. .cookie("auth", "token") //設置cookie
  7. .timeout(3000) //設置連接超時時間
  8. .post(); //使用POST方法訪問URL

說明:

  1. connect(String url) 方法創建一個新的 Connection 和 get() 取得和解析一個HTML文件。如果從該URL獲取HTML時發生錯誤,便會拋出 IOException,應適當處理。
  2. Connection 接口還提供一個方法鏈來解決特殊請求,具體如下:

 
  1. Document doc = Jsoup.connect("http://example.com")
  2. .data("query", "Java")
  3. .userAgent("Mozilla")
  4. .cookie("auth", "token")
  5. .timeout(3000)
  6. .post();

這個方法只支持Web URLs (http 和 https 協議); 假如你需要從一個文件加載,可以使用 parse(File in, String charsetName) 代替。

1.3 從文件中加載HTML文檔

在本機硬盤上有一個HTML文件,需要對它進行解析從中抽取數據或進行修改。可以使用靜態 Jsoup.parse(File in, String charsetName, String baseUri) 方法。


 
  1. File input = new File("/tmp/input.html");
  2. Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

說明:

  1. parse(File in, String charsetName, String baseUri) 這個方法用來加載和解析一個HTML文件。如在加載文件的時候發生錯誤,將拋出IOException,應作適當處理。

  2. baseUri參數用於解決文件中URLs是相對路徑的問題。如果不需要可以傳入一個空的字符串。

  3. 另外還有一個方法parse(File in, String charsetName) 它使用文件的路徑做爲 baseUri。 這個方法適用於如果被解析文件位於網站的本地文件系統,且相關鏈接也指向該文件系統。

1.4 保證安全Stay safe

假如你可以讓用戶輸入HTML內容,那麼要小心避免跨站腳本攻擊。利用基於Whitelist的清除器和clean(String bodyHtml, Whitelist whitelist) 方法來清除用戶輸入的惡意內容。

詳情查看 第4節 [4.HTML清理](#4.HTML清理)

2. 數據抽取

2.1 使用DOM方法來遍歷一個文檔

有一個HTML文檔要從中提取數據,並瞭解這個HTML文檔的結構。將HTML解析成一個Document之後,就可以使用類似於DOM的方法進行操作。


 
  1. File input = new File("/tmp/input.html");
  2. Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
  3.  
  4. Element content = doc.getElementById("content");
  5. Elements links = content.getElementsByTag("a");
  6. for (Element link : links) {
  7. String linkHref = link.attr("href");
  8. String linkText = link.text();
  9. }

說明:Elements這個對象提供了一系列類似於DOM的方法來查找元素,抽取並處理其中的數據。具體如下:

2.1.1 查找元素

getElementById(String id) id
getElementsByTag(String tag) 標籤名
getElementsByClass(String className) class名
getElementsByAttribute(String key) 屬性
siblingElements() 所有的兄弟元素
firstElementSibling() 第一個兄弟元素
lastElementSibling() 最後一個兄弟元素
nextElementSibling() 下一個兄弟元素
previousElementSibling() 上一個兄弟元素
parent() 獲取該元素父節點
children() 獲取該元素的子元素
child(int index) 獲取該元素的第幾個子元素(下標從0開始)

2.1.2 元素數據

attr(String key) 獲取屬性
attr(String key, String value) 設置屬性
attributes() 獲取所有屬性
id() 獲取該元素id
className() 獲取該元素class,多個class之間空格隔開
classNames() 獲取所有元素的class
text() 獲取文本內容
text(String value) 設置文本內容
html() 獲取元素內HTML
html(String value) 設置元素內的HTML內容
outerHtml() 獲取元素外HTML內容
data() 獲取數據內容(例如:script和style標籤)
tag()  
tagName() 獲取元素標籤名

2.1.3 操作HTML和文本

append(String html) 添加給定的html到元素末尾
prepend(String html) 添加給定html到元素前面
appendText(String text) 創建並添加文本
prependText(String text) 創建並添加文本
appendElement(String tagName) 添加到元素末尾
prependElement(String tagName) 添加到元素前
html(String value) 設置元素值

2.2 使用選擇器語法來查找元素(select)

使用 Element.select(String selector) 和 Elements.select(String selector),使用類似於CSS或jQuery的語法來查找和操作元素。


 
  1. File input = new File("/tmp/input.html");
  2. Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
  3. Elements links = doc.select("a[href]"); //帶有href屬性的a元素
  4. Elements pngs = doc.select("img[src$=.png]"); //擴展名爲.png的圖片
  5. Element masthead = doc.select("div.masthead").first();//class等於masthead的div標籤
  6. Elements resultLinks = doc.select("h3.r > a"); //在h3元素之後的a元素

說明: 
jsoup elements對象支持類似於CSS (或jquery)的選擇器語法,來實現非常強大和靈活的查找功能。

這個select 方法在DocumentElement,或Elements 對象中都可以使用。且是上下文相關的,因此可實現指定元素的過濾,或者鏈式選擇訪問。

Select方法將返回一個Elements 集合,並提供一組方法來抽取和處理結果。

2.2.1 Selector選擇器 基本用法

tagname 使用標籤名來定位,例如 a
ns|tag 使用命名空間的標籤定位,例如 fb:name 來查找 <fb:name> 元素
#id 使用元素 id 定位,例如 #logo
.class 使用元素的 class 屬性定位,例如 .head
[attribute] 使用元素的屬性進行定位,例如 [href] 表示檢索具有 href 屬性的所有元素
[^attr] 使用元素的屬性名前綴進行定位,例如 [^data-] 用來查找 HTML5 的 dataset 屬性
[attr=value] 使用屬性值進行定位,例如 [width=500] 定位所有 width 屬性值爲 500 的元素
[attr^=value], [attr$=value], [attr*=value] 利用匹配屬性值開頭、結尾或包含屬性值來查找元素,比如:[href*=/path/]
[attr~=regex] 利用屬性值匹配正則表達式來查找元素,例如img[src~=(?i).(png|jpe?g)]
* 定位所有元素

2.2.2 Selector選擇器 組合使用

el#id 定位 id 值某個元素,例如 a#logo -> <a id=logo href= … >
el.class 定位 class 爲指定值的元素,例如 div.head -> <div class=head>xxxx</div>
el[attr] 定位所有定義了某屬性的元素,例如 a[href]
以上三個任意組合 例如 a[href]#logo 、a[name].outerlink
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

2.2.3 僞選擇器selectors (表達式):

: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) 使用正則表達式找到自身的文本
  • 注意:上述僞選擇器索引是從0開始的,也就是說第一個元素索引值爲0,第二個元素index爲1等
  • 可以查看Selector API參考來了解更詳細的內容

2.3 從元素抽取屬性,文本和HTML


 
  1. String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
  2. Document doc = Jsoup.parse(html);//解析HTML字符串返回一個Document實現
  3. Element link = doc.select("a").first();//查找第一個a元素
  4.  
  5. String text = doc.body().text(); // "An example link"//取得字符串中的文本
  6. String linkHref = link.attr("href"); // "http://example.com/"//取得鏈接地址
  7. String linkText = link.text(); // "example""//取得鏈接地址中的文本
  8.  
  9. String linkOuterH = link.outerHtml();
  10. // "<a href="http://example.com"><b>example</b></a>"
  11. String linkInnerH = link.html(); // "<b>example</b>"//取得鏈接內的html內容

說明: 
上述方法是元素數據訪問的核心辦法。此外還其它一些方法可以使用:

這些訪問器方法都有相應的setter方法來更改數據.

2.4 處理URLs

有一個包含相對URLs路徑的HTML文檔,需要將這些相對路徑轉換成絕對路徑的URLs。

  1. 在解析文檔時確保有指定baseURI
  2. 然後使用 abs: 屬性前綴來取得包含baseURI的絕對路徑

 
  1. Document doc = Jsoup.connect("http://www.open-open.com").get();
  2. Element link = doc.select("a").first();
  3. String relHref = link.attr("href"); // == "/"
  4. 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文檔時,定義baseURI非常重要。

如果你不想使用abs: 前綴,還有一個方法能夠實現同樣的功能 Node.absUrl(String key)

2.5 示例程序: 獲取所有鏈接

這個示例程序將展示如何從一個URL獲得一個頁面。然後提取頁面中的所有鏈接、圖片和其它輔助內容。並檢查URLs和文本信息。運行下面程序需要指定一個URLs作爲參數


 
  1. package org.jsoup.examples;
  2.  
  3. import org.jsoup.Jsoup;
  4. import org.jsoup.helper.Validate;
  5. import org.jsoup.nodes.Document;
  6. import org.jsoup.nodes.Element;
  7. import org.jsoup.select.Elements;
  8.  
  9. import java.io.IOException;
  10.  
  11. /**
  12. * Example program to list links from a URL.
  13. */
  14. public class ListLinks {
  15. public static void main(String[] args) throws IOException {
  16. Validate.isTrue(args.length == 1, "usage: supply url to fetch");
  17. String url = args[0];
  18. print("Fetching %s...", url);
  19.  
  20. Document doc = Jsoup.connect(url).get();
  21. Elements links = doc.select("a[href]");
  22. Elements media = doc.select("[src]");
  23. Elements imports = doc.select("link[href]");
  24.  
  25. print("\nMedia: (%d)", media.size());
  26. for (Element src : media) {
  27. if (src.tagName().equals("img"))
  28. print(" * %s: <%s> %sx%s (%s)",
  29. src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
  30. trim(src.attr("alt"), 20));
  31. else
  32. print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
  33. }
  34.  
  35. print("\nImports: (%d)", imports.size());
  36. for (Element link : imports) {
  37. print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel"));
  38. }
  39.  
  40. print("\nLinks: (%d)", links.size());
  41. for (Element link : links) {
  42. print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35));
  43. }
  44. }
  45.  
  46. private static void print(String msg, Object... args) {
  47. System.out.println(String.format(msg, args));
  48. }
  49.  
  50. private static String trim(String s, int width) {
  51. if (s.length() > width)
  52. return s.substring(0, width-1) + ".";
  53. else
  54. return s;
  55. }
  56. }

示例輸入結果:


 
  1. Fetching http://news.ycombinator.com/...
  2.  
  3. Media: (38)
  4. * img: <http://ycombinator.com/images/y18.gif> 18x18 ()
  5. * img: <http://ycombinator.com/images/s.gif> 10x1 ()
  6. * img: <http://ycombinator.com/images/grayarrow.gif> x ()
  7. * img: <http://ycombinator.com/images/s.gif> 0x10 ()
  8. * script: <http://www.co2stats.com/propres.php?s=1138>
  9. * img: <http://ycombinator.com/images/s.gif> 15x1 ()
  10. * img: <http://ycombinator.com/images/hnsearch.png> x ()
  11. * img: <http://ycombinator.com/images/s.gif> 25x1 ()
  12. * img: <http://mixpanel.com/site_media/images/mixpanel_partner_logo_borderless.gif> x (Analytics by Mixpan.)
  13.  
  14. Imports: (2)
  15. * link <http://ycombinator.com/news.css> (stylesheet)
  16. * link <http://ycombinator.com/favicon.ico> (shortcut icon)
  17.  
  18. Links: (141)
  19. * a: <http://ycombinator.com> ()
  20. * a: <http://news.ycombinator.com/news> (Hacker News)
  21. * a: <http://news.ycombinator.com/newest> (new)
  22. * a: <http://news.ycombinator.com/newcomments> (comments)
  23. * a: <http://news.ycombinator.com/leaders> (leaders)
  24. * a: <http://news.ycombinator.com/jobs> (jobs)
  25. * a: <http://news.ycombinator.com/submit> (submit)
  26. * a: <http://news.ycombinator.com/x?fnid=JKhQjfU7gW> (login)
  27. * a: <http://news.ycombinator.com/vote?for=1094578&dir=up&whence=%6e%65%77%73> ()
  28. * 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)
  29. * a: <http://news.ycombinator.com/user?id=mcxx> (mcxx)
  30. * a: <http://news.ycombinator.com/item?id=1094578> (9 comments)
  31. * a: <http://news.ycombinator.com/vote?for=1094649&dir=up&whence=%6e%65%77%73> ()
  32. * a: <http://groups.google.com/group/django-developers/msg/a65fbbc8effcd914> ("Tough. Django produces XHTML.")
  33. * a: <http://news.ycombinator.com/user?id=andybak> (andybak)
  34. * a: <http://news.ycombinator.com/item?id=1094649> (3 comments)
  35. * a: <http://news.ycombinator.com/vote?for=1093927&dir=up&whence=%6e%65%77%73> ()
  36. * a: <http://news.ycombinator.com/x?fnid=p2sdPLE7Ce> (More)
  37. * a: <http://news.ycombinator.com/lists> (Lists)
  38. * a: <http://news.ycombinator.com/rss> (RSS)
  39. * a: <http://ycombinator.com/bookmarklet.html> (Bookmarklet)
  40. * a: <http://ycombinator.com/newsguidelines.html> (Guidelines)
  41. * a: <http://ycombinator.com/newsfaq.html> (FAQ)
  42. * a: <http://ycombinator.com/newsnews.html> (News News)
  43. * a: <http://news.ycombinator.com/item?id=363> (Feature Requests)
  44. * a: <http://ycombinator.com> (Y Combinator)
  45. * a: <http://ycombinator.com/w2010.html> (Apply)
  46. * a: <http://ycombinator.com/lib.html> (Library)
  47. * a: <http://www.webmynd.com/html/hackernews.html> ()
  48. * a: <http://mixpanel.com/?from=yc> ()

3. 數據修改

3.1 設置屬性的值

在解析一個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");

3.2 設置一個元素的HTML內容


 
  1. Element div = doc.select("div").first(); // <div></div>
  2. div.html("<p>lorem ipsum</p>"); // <div><p>lorem ipsum</p></div>
  3. div.prepend("<p>First</p>");//在div前添加html內容
  4. div.append("<p>Last</p>");//在div之後添加html內容
  5. // 添完後的結果: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>
  6.  
  7. Element span = doc.select("span").first(); // <span>One</span>
  8. span.wrap("<li><a href='http://example.com/'></a></li>");
  9. // 添完後的結果: <li><a href="http://example.com"><span>One</span></a></li>

說明:

3.3 設置元素的文本內容


 
  1. Element div = doc.select("div").first(); // <div></div>
  2. div.text("five > four"); // <div>five &gt; four</div>
  3. div.prepend("First ");
  4. div.append(" Last");
  5. // now: <div>First five &gt; four Last</div>

說明: 
文本設置方法與 HTML setter 方法一樣:

對於傳入的文本如果含有像 <> 等這樣的字符,將以文本處理,而非HTML。

4.HTML清理

4.1 消除不受信任的HTML (防止XSS攻擊)

在做網站的時候,經常會提供用戶評論的功能。有些不懷好意的用戶,會搞一些腳本到評論內容中,而這些腳本可能會破壞整個頁面的行爲,更嚴重的是獲取一些機要信息,此時需要清理該HTML,以避免跨站腳本cross-site scripting攻擊(XSS)。 
使用jsoup HTML Cleaner 方法進行清除,但需要指定一個可配置的 Whitelist


 
  1. String unsafe = "<p><a href='http://example.com/' οnclick='stealCookies()'>Link</a></p>";
  2. String safe = Jsoup.clean(unsafe, Whitelist.basic());
  3. // 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攻擊,還可以限制用戶可以輸入的標籤範圍。

jsoup 使用一個 Whitelist 類用來對 HTML 文檔進行過濾,該類提供幾個常用方法:

4.2 whitelist常用方法

API查看:Whitelist

方法名 簡介
none() 只允許包含文本信息
basic() 允許的標籤包括:a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li, ol, p, pre, q, small, strike, strong, sub, sup, u, ul, 以及合適的屬性
simpleText() 只允許 b, em, i, strong, u 這些標籤
basicWithImages() 在 basic() 的基礎上增加了圖片
relaxed() 這個過濾器允許的標籤最多,包括:a, b, blockquote, br, caption, cite, code, col, colgroup, dd, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, u, ul

如果這五個過濾器都無法滿足你的要求呢,例如你允許用戶插入 flash 動畫,沒關係,Whitelist 提供擴展功能,例如 whitelist.addTags("embed","object","param","span","div"); 也可調用 addAttributes 爲某些元素增加屬性。

參考:

  • 參閱XSS cheat sheet ,有一個例子可以瞭解爲什麼不能使用正則表達式,而採用安全的whitelist parser-based清理器纔是正確的選擇。
  • 參閱Cleaner ,瞭解如何返回一個 Document 對象,而不是字符串
  • 參閱Whitelist,瞭解如何創建一個自定義的whitelist
  • nofollow 鏈接屬性瞭解

5.更多參考

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章