html parser html解析

对html的解析我的要求非常简单,就是形成tag=>text的对应关系,如下:
<html>
<head>
<title>title content</title>
<meta values="meta content">
</head>
<body>
body content
<p>p content</p>
<a href="first link"></a>
<a href="second link"></a>
<a href="third link"></a>
</body>
</html>


解析之后:
html=>null
title=>title content
meta=>meta
body=>body content
p=>p content
a=>[ first link
second link
third link
]


[color=gray](之所以使用tag=>text的方式,是因为在搜索中,不同的tag的文本对应的权重不一样,比如<meta content="text"> <p>text</p>两个元素中text权重显然不是一样的)[/color]
这里我使用了htmlparser jar包,使用了递归,程序代码如下:
/*init:
content = new StringBuilder();
title = new StringBuilder();
meta = new StringBuilder();
big = new StringBuilder();
link = new ArrayList();
*/

public void processNode(Node node ,String tag){
tag = tag.toLowerCase().trim();
NodeList list = node.getChildren();
if(list == null){
return;
}

for(int i=0;i<list.size();i++){
Node childnode = list.elementAt(i);
if(childnode instanceof TextNode){
String text = childnode.getText();
text = text.replaceAll("\\s+", " ");
text = text.replaceAll(" |>|<", "");
text = text.trim();

if(text.matches(" +")){
continue;
}

if(text == null || text.isEmpty()){
continue;
}

if(tag.matches("head|title")){
title.append(" " + text);
}else if(tag.matches("meta")){
meta.append(" " + text);
}else if(tag.matches("big|h\\d|b|i|u|strong|font|li")){
big.append(" " + text);
}else if(tag.matches("a")){
big.append(" " + text);
}else if(tag.matches("script|style")){
return;
}else{
content.append(" " + text);
}
}else if(childnode instanceof TagNode){
String childtag = ((TagNode) childnode).getRawTagName();
childtag = childtag.toLowerCase().trim();

if(childtag.equals("meta")){
if( ((TagNode) childnode).getAttribute("http-equiv") == null ){
String value = ((TagNode) childnode).getAttribute("value") ;
String content = ((TagNode) childnode).getAttribute("content") ;
if( content != null){
meta.append(content);
}
if(value != null){
meta.append(value);
}
}
}else if(childtag.equals("a")){
String href = ((TagNode) childnode).getAttribute("href") ;
if(href.isEmpty()){
continue;
}
if(!href.startsWith("http")){
href = (url + "/" + href);
}
href = href.replaceAll("/$", "");
if(urlfilter.filter(href)){
link.add(href);
//System.out.println("in:" + href);
}else{
//System.out.println("out:" + href);
}
}
processNode(childnode,childtag);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值