HtmlParser技術 網頁抓取

2021-06-22 18:16:18 字數 2656 閱讀 1105

網頁採集程式:

如果是整個網頁儲存到本地/讀取的話,直接用outputstrem和inputstream讀取

htmlparser用來做網頁的分析和內容提取特別方法

htmlparser具有小巧,快速的優點,缺點是相關文件比較少(英文的也少),很多功能需要自己摸索。對於初學者還是要費一些功夫的,而一旦上手以後,會發現htmlparser的結構設計很巧妙,非常實用,基本你的各種需求都可以滿足。

例子:

private static mapgetsubmenumap(string weburl) 

if (isaccess == true)

}} catch (exception e)

return menumap;

}

htmlparser的核心模組是org.htmlparser.parser類,這個類實際完成了對於html頁面的分析工作。這個類有下面幾個建構函式:

public parser ();

public parser (lexer lexer, parserfeedback fb);

public parser (urlconnection connection, parserfeedback fb) throws parserexception;

public parser (string resource, parserfeedback feedback) throws parserexception;

public parser (string resource) throws parserexception;

public parser (lexer lexer);

public parser (urlconnection connection) throws parserexception;

和乙個靜態類public static parser createparser (string html, string charset);

(一)filter類

顧名思義,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

node中包含的方法有幾類:

對於樹型結構進行遍歷的函式,這些函式最容易理解:

node getparent ():取得父節點

nodelist getchildren ():取得子節點的列表

node getfirstchild ():取得第乙個子節點

node getlastchild ():取得最後乙個子節點

node getprevioussibling ():取得前乙個兄弟(不好意思,英文是兄弟姐妹,直譯太麻煩而且不符合習慣,對不起女同胞了)

取得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頁面中的結束位置

用於filter過濾的函式:

void collectinto (nodelist list, nodefilter filter):基於filter的條件對於這個節點進行過濾,符合條件的節點放到list中。

用於visitor遍歷的函式:

void accept (nodevisitor visitor):對這個node應用visitor

用於修改內容的函式,這類用得比較少:

void setpage (page page):設定這個node對應的page物件

void settext (string text):設定文字

void setchildren (nodelist children):設定子節點列表

其他函式:

void dosemanticaction ():執行這個node對應的操作(只有少數tag有對應的操作)

object clone ():介面clone的抽象函式。

更多的詳情 參考:

利用htmlparser抓取網頁內容

import org.htmlparser.node import org.htmlparser.nodefilter import org.htmlparser.parser import org.htmlparser.filters.tagnamefilter import org.htmlpa...

htmlparser分析網頁鏈結時的問題

利用htmlparser在解析網頁的url鏈結時,我們想提取指定標籤下的鏈結。例如 div id wrap下的鏈結,可以通過下面 實現 parser parser new parser url nodefilter nodefilter1 new andfilter new tagnamefilte...

網頁抓包工具 HttpWatch

做為一名web開發者,需要經常分析網頁傳送的資料報,而httpwatch做為一款ie的強勁外掛程式,短小精悍,就能很好地完成url請求的分析,網頁摘要.cookies管理.快取管理.訊息頭髮送 接受.字元查詢.post 資料和目錄管理功能.報告輸出。httpwatch最主要的功能就是對通過瀏覽器傳送...