標籤:style class c code java tar
1、相關資料
官方文檔:http://htmlparser.sourceforge.net/samples.html
API:http://htmlparser.sourceforge.net/javadoc/index.html
其它HTML 解譯器:jsoup等。由於HtmlParser自2006年以後就再沒更新,目前很多人推薦使用jsoup代替它。
2、使用HtmlPaser的關鍵步驟
(1)通過Parser類建立一個解譯器
(2)通過Filter或者Vistor訪問Html中的內容。
3、使用Parser的建構函式建立解譯器
Parser()
Zero argument constructor. |
Parser(Lexer lexer)
Construct a parser using the provided lexer. |
Parser(Lexer lexer, ParserFeedback fb)
Construct a parser using the provided lexer and feedback object. |
Parser(String resource)
Creates a Parser object with the location of the resource (URL or file). |
Parser(String resource, ParserFeedback feedback)
Creates a Parser object with the location of the resource (URL or file) You would typically create a DefaultHTMLParserFeedback object and pass it in. |
Parser(URLConnection connection)
Construct a parser using the provided URLConnection. |
Parser(URLConnection connection, ParserFeedback fb)
Constructor for custom HTTP access. |
對於大多數使用者來說,使用最多的是通過一個URLConnection或者一個儲存有網頁內容的字串來初始化Parser,或者使用靜態函數來產生一個Parser對象。ParserFeedback的代碼很簡單,是針對調試和跟蹤分析過程的,一般不需要改變。而使用Lexer則是一個相對比較進階的話題,放到以後再討論吧。
這裡比較有趣的一點是,如果需要設定頁面的編碼方式的話,不使用Lexer就只有靜態函數一個方法了。對於大多數中文頁面來說,好像這是應該用得比較多的一個方法。
4、HtmlPaser使用Node對象儲存各節點資訊
(1)訪問各個節點的方法
Node getParent ():取得父節點
NodeList getChildren ():取得子節點的列表
Node getFirstChild ():取得第一個子節點
Node getLastChild ():取得最後一個子節點
Node getPreviousSibling ():取得前一個兄弟(不好意思,英文是兄弟姐妹,直譯太麻煩而且不符合習慣,對不起女同胞了)
Node getNextSibling ():取得下一個兄弟節點
(2)取得Node內容的函數
String getText ():取得文本
String toPlainTextString():取得純文字資訊。
String toHtml () :取得HTML資訊(原始HTML)
String toHtml (boolean verbatim):取得HTML資訊(原始HTML)
String toString ():取得字串資訊(原始HTML)
Page getPage ():取得這個Node對應的Page對象
int getStartPosition ():取得這個Node在HTML頁面中的起始位置
int getEndPosition ():取得這個Node在HTML頁面中的結束位置
5、使用Filter訪問Node節點及其內容
(1)Filter的種類
顧名思義,Filter就是對於結果進行過濾,取得需要的內容。
所有的Filter均實現了NodeFilter介面,此介面只有一個方法Boolean accept(Node node),用於確定某個節點是否屬於此Filter過濾的範圍。
HTMLParser在org.htmlparser.filters包之內一共定義了16個不同的Filter,也可以分為幾類。
判斷類Filter:
TagNameFilter
HasAttributeFilter
HasChildFilter
HasParentFilter
HasSiblingFilter
IsEqualFilter
邏輯運算Filter:
AndFilter
NotFilter
OrFilter
XorFilter
其他Filter:
NodeClassFilter
StringFilter
LinkStringFilter
LinkRegexFilter
RegexFilter
CssSelectorNodeFilter
除此以外,可以自訂一些Filter,用於完成特殊需求的過濾。
(2)Filter的使用樣本
在