HtmlParser实例解析:
网页内容:
<td width="100%" colspan="3" height="20" align="center">
<font color="#000080" style="font-size:14.4px"><b>教材征订及教师用书登记通知</b></font>
<hr noshade size="1" color="#FFFFFF">阅读量:<font color="#808080">1111</font>
发布时间:<font color="#808080">2006-5-12 21:24:36</font>
</td>
实现代码如下:
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import org.htmlparser.Node;
- import org.htmlparser.NodeFilter;
- import org.htmlparser.filters.AndFilter;
- import org.htmlparser.filters.HasChildFilter;
- import org.htmlparser.filters.TagNameFilter;
- import org.htmlparser.util.NodeList;
- import com.extractor.Extractor;
- public class ExtractorHangdian extends Extractor{
- public void extract()
- {
- BufferedWriter bw=null;
- String title;
- //NodeFilter title_filter=new AndFilter(new TagNameFilter("font"),new HasAttributeFilter("color","#000080"));
- NodeFilter title_filter1=new AndFilter(new TagNameFilter("td"),new HasChildFilter(new TagNameFilter("b")));
- try
- {
- /*NodeList title_nodes=this.getParser().parse(title_filter);
- Node title_node=title_nodes.elementAt(0);
- title=title_node.getNextSibling().getNextSibling().toHtml();
- */
- NodeList title_nodes=this.getParser().parse(title_filter1);
- Node node=title_nodes.elementAt(0);
- NodeList node2=node.getChildren();
- title=node2.elementAt(0).toHtml(); /* '/r/n' */
- title=node2.elementAt(1).toHtml(); /*font color="#000080" style="font-size:14.4px*/
- title=node2.elementAt(2).toHtml(); /* b */
- title=node2.elementAt(3).toHtml(); /* 教材征订及教师用书登记通知 */
- bw=new BufferedWriter(new FileWriter(new File(this.getOutputPath()+title+".txt")));
- bw.write(title);
- bw.close();
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
上代码中注释掉的那部分也是正确的,呵呵……