Posted on 2010-04-23 17:38
泰仔在線 閱讀(3074)
評論(1) 編輯 收藏 所屬分類:
云計算相關
今天主要研究了Nutch中的html頁面的解析問題,因為我的任務是從頁面中提取特定的文本,因此首先要找到Nutch如何將html中的文本提取出來。Nutch提供了兩種html解析器,nekohtml和tagsoup,我采用了neko的解析器,在看了代碼后,發現其提取文本的方法在org.apache.nutch.parse.html中的DOMContentUtils文件中,主要的函數是getTextHelper。下面做一下解釋。
private boolean getTextHelper(StringBuffer sb, Node node,
boolean abortOnNestedAnchors,
int anchorDepth) {
boolean abort = false;
NodeWalker walker = new NodeWalker(node);// NodeWalk類用來非遞歸遍歷DOM樹節點
int myint=1;
while (walker.hasNext()){ //如果存在節點
Node currentNode = walker.nextNode();//獲取下一個節點
String nodeName = currentNode.getNodeName();//獲取節點名
short nodeType = currentNode.getNodeType();//節點類型
if ("script".equalsIgnoreCase(nodeName)) {//不處理腳本
walker.skipChildren();
}
if ("style".equalsIgnoreCase(nodeName)) {//不處理style
walker.skipChildren();
}
if (abortOnNestedAnchors && "a".equalsIgnoreCase(nodeName)) {//檢測是否嵌套
anchorDepth++;
if (anchorDepth > 1) {
abort = true;
break;
}
}
if (nodeType == Node.COMMENT_NODE) {//不處理注釋
walker.skipChildren();
}
if (nodeType == Node.TEXT_NODE) {
// cleanup and trim the value
String text = currentNode.getNodeValue();//獲取文本內容
text = text.replaceAll("\\s+", " ");//消除所有空格和轉行等字符
text = text.trim();
if (text.length() > 0) {
if (sb.length() > 0) sb.append(' ');
sb.append(text);
}
}
}
}
調用這個函數的類是htmlParser類,如果想自己寫一個提取文本的函數,可以做相應修改。
轉自:
實習日記(六)