需要两个包htmllexer.jar和htmlparser.jar
实例源码
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasChildFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.http.ConnectionManager;
import org.htmlparser.lexer.Page;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
public class FilterTest {
public static void main(String[] args){
ConnectionManager manager;
try{
manager = Page.getConnectionManager();
Parser parser = new Parser(manager.openConnection("http://www.hzau.edu.cn"));
parser.setEncoding("utf-8");
//AndFilter 接受所有同时满足2个Filter的节点
//HasChildFilter接受所有子节点符合该Filter的节点
//TagNameFilter接受所有满足Tag名的Tag Nodes
NodeFilter filter = new AndFilter(new TagNameFilter("a"),new HasChildFilter(new TagNameFilter("img")));
//System.out.println(filter);
NodeList nodelist = parser.parse(filter);
//System.out.println(nodelist);
//NodeIterator访问所有节点
NodeIterator it= nodelist.elements();
//System.out.println(it);
while(it.hasMoreNodes()){
Node node = (Node)it.nextNode();
System.out.println(node.toHtml());
}
}catch(ParserException e){
e.printStackTrace();
}
}
}