java使用htmlparser提取网页纯文本例子
package 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() {
try {
String sCurrentLine;
String sTotalString;
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 (Exception e) {
e.printStackTrace();
}
}
public static String extractText(String inputHtml) throws Exception {
StringBuffer text = new StringBuffer();
Parser parser = Parser.createParser(new String(inputHtml.getBytes(),"GBK"), "GBK");
// 遍历所有的节点
NodeList nodes = parser.extractAllNodesThatMatch(new NodeFilter() {
public boolean accept(Node node) {
return 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) throws Exception {
Parser myParser = new Parser(resource);
myParser.setEncoding("GBK");
String filterStr = "table";
NodeFilter filter = new TagNameFilter(filterStr);
NodeList nodeList = myParser.extractAllNodesThatMatch(filter);
TableTag tabletag = (TableTag) nodeList.elementAt(11);
}
public static void main(String[] args) throws Exception {
// test5("http://www.google.com");
testHtml();
}
}
相关文章
详解Java ReentrantLock可重入,可打断,锁超时的实现原理
前面讲解了ReentrantLock加锁和解锁的原理实现,但是没有阐述它的可重入、可打断以及超时获取锁失败的原理,本文就重点讲解这三种情况,需要的可以了解一下2022-10-10Spring IoC学习之ApplicationContext中refresh过程详解
这篇文章主要给大家介绍了关于Spring IoC学习之ApplicationContext中refresh过程的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-09-09基于Spring-cloud-gateway实现全局日志记录的方法
最近项目在线上运行出现了一些难以复现的bug需要定位相应api的日志,通过nginx提供的api请求日志难以实现,于是在gateway通过全局过滤器记录api请求日志,本文给大家介绍基于Spring-cloud-gateway实现全局日志记录,感兴趣的朋友一起看看吧2023-11-11
最新评论