天天看點

JAVA中使用Htmlparse解析HTML文檔

import java.util.hashmap;  

import java.util.map;  

import org.htmlparser.node;  

import org.htmlparser.nodefilter;  

import org.htmlparser.parser;  

import org.htmlparser.tags.linktag;  

import org.htmlparser.util.nodelist;  

import com.yao.http.httprequester;  

import com.yao.http.httprespons;  

/** 

 * java中使用htmlparse解析html文檔,使用htmlparse周遊出html文檔的所有超連結(<a>标記)。 

 *  

 * @author yymmiinngg 

 */  

public class test {  

    public static void main(string[] args) {  

        try {  

/* 首先我們先使用httprequester類和httprespons類獲得一個http請求中的資料(html文檔)。 可以從(http://download.csdn.net/source/321516)中下載下傳htmlloader,該庫中有上述類;或從我的《java發送http請求,傳回http響應内容,執行個體及應用》一文中摘取上述兩java類的代碼。htmlparse可以從(http://download.csdn.net/source/321507)中下載下傳 

*/  

            map<string, string> map = new hashmap<string, string>();  

            httprequester request = new httprequester();  

            httprespons hr = request.sendget("http://www.baidu.com");  

            parser parser = parser.createparser(hr.getcontent(), hr  

                    .getcontentencoding());  

            try {  

                // 通過過濾器過濾出<a>标簽  

                nodelist nodelist = parser  

                        .extractallnodesthatmatch(new nodefilter() {  

                            //實作該方法,用以過濾标簽  

                            public boolean accept(node node) {  

                                if (node instanceof linktag)//<a>标記  

                                    return true;  

                                return false;  

                            }  

                        });  

                // 列印  

                for (int i = 0; i < nodelist.size(); i++) {  

                    linktag n = (linktag) nodelist.elementat(i);  

                    system.out.print(n.getstringtext() + " ==>> ");  

                    system.out.println(n.extractlink());  

                }  

            } catch (exception e) {  

                e.printstacktrace();  

            }  

        } catch (exception e) {  

            e.printstacktrace();  

        }  

    }  

}  

上一篇: SQL 語句大全
下一篇: HTTP協定