复制代码代码如下:
パッケージcom.test;
Import org.htmlparser.node;
Import org.htmlparser.nodefilter;
Import org.htmlparser.parser;
Import org.htmlparser.filters.tagnamefilter;
Import org.htmlparser.tags.tabletag;
Import org.htmlparser.util.nodelist;
/**
*标题:利用htmlparser提取网页纯文本的例子
*/
public class testhtmlparser {
public static void testhtml(){
試す {
文字列scurrentline;
ストリングストートールストリング;
scurrentline = "";
StotalString = "";
java.io.inputStream l_urlstream;
java.net.url l_url = new java.net.url( "http://www.ideagrace.com/html/doc/2006/07/04/00929.html");
java.net.httpurlconnection l_connection =(java.net.httpurlconnection)l_url.openconnection();
l_connection.connect();
l_urlstream = l_connection.getInputStream();
java.io.BufferedReader l_reader = new Java.io.BufferedReader(new java.io.inputStreamReader(l_urlstream));
while((scurrentline = l_reader.readline())!= null){
StotalString += scurrentline +"/r/n";
// System.out.println(StotalString);
}
string testText = ExtractText(StotalString);
System.out.println(testText);
} catch(例外e){
e.printstacktrace();
}
}
public static string抽出物(string inputhtml)スロー例外{
stringbuffer text = new StringBuffer();
parser parser = parser.createparser(new String(inputhtml.getBytes()、 "gbk")、 "gbk");
//遍历所有的节点
nodeList nodes = parser.extractallnodesthatmatch(new nodefilter(){
public boolean Accept(ノードノード){
trueを返します。
}
});
system.out.println(nodes.size()); //打印节点的数量
for(int i = 0; i <nodes.size(); i ++){
node nodet = nodes.elementat(i);
//system.out.println(nodet.getText());
text.append(new String(nodet.toplaintextString()。getBytes( "gbk"))+"/r/n");
}
return text.toString();
}
public static void test5(string resource)スロー例外{
パーサーmyparser = new Parser(リソース);
myparser.setencoding( "gbk");
文字列filterstr = "table";
nodefilter filter = new tagnamefilter(filterstr);
nodeList nodeList = myparser.extractallnodesthatmatch(フィルター);
TableTag TableTag =(TableTag)nodeList.Elementat(11);
}
public static void main(string [] args)スロー例外{
// test5( "http://www.google.com");
testhtml();
}
}