posts - 297,  comments - 1618,  trackbacks - 0
                 出處:http://blog.csdn.net/redez/archive/2005/11/21/534277.aspx
                 說明:本文參考HTMLParser使用,并在該文的基礎上進行了部分修改。
          一. 簡介
                 htmlparser用于 對html頁面進行解析,它是一個功能比較強大的工具。
                 項目首頁http://htmlparser.sourceforge.net/
                 下載地址http://sourceforge.net/project/showfiles.php?group_id=24399
          二. 使用舉例
                 下面通過一個簡單的htmlparser的使用舉例,來學習htmlparser的使用。代碼如下:
          package com.amigo.htmlparser;

          import java.io.*;
          import java.net.URL;
          import java.net.URLConnection;

          import org.htmlparser.filters.*;
          import org.htmlparser.*;
          import org.htmlparser.nodes.*;
          import org.htmlparser.tags.*;
          import org.htmlparser.util.*;
          import org.htmlparser.visitors.*;

          /**
           * 測試HTMLParser的使用.
           * 
          @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
           * Creation date: 2008-1-18 - 上午11:44:22
           
          */

          public class HTMLParserTest {
              
          /**
               * 入口方法.
               * 
          @param args
               * 
          @throws Exception
               
          */

              
          public static void main(String args[]) throws Exception {
                  String path 
          = "http://www.aygfsteel.com/amigoxie";
                  URL url 
          = new URL(path);
                  URLConnection conn 
          = url.openConnection();
                  conn.setDoOutput(
          true); 
                  
                  InputStream inputStream 
          = conn.getInputStream();
                  InputStreamReader isr 
          = new InputStreamReader(inputStream, "utf8");
                  StringBuffer sb 
          = new StringBuffer();
                  BufferedReader in 
          = new BufferedReader(isr);
                  String inputLine;
                  
                  
          while ((inputLine = in.readLine()) != null{
                      sb.append(inputLine);
                      sb.append(
          "\n");
                  }

                  
                  String result 
          = sb.toString();

                  readByHtml(result);
                  readTextAndLinkAndTitle(result);
              }

              
              
          /**
               * 按頁面方式處理.解析標準的html頁面
               * 
          @param content 網頁的內容
               * 
          @throws Exception
               
          */

              
          public static void readByHtml(String content) throws Exception {
                  Parser myParser;
                  myParser 
          = Parser.createParser(content, "utf8");
                  HtmlPage visitor 
          = new HtmlPage(myParser);
                  myParser.visitAllNodesWith(visitor);

                  String textInPage 
          = visitor.getTitle();
                  System.out.println(textInPage);
                  NodeList nodelist;
                  nodelist 
          = visitor.getBody();
                  
                  System.out.print(nodelist.asString().trim());
              }


              
          /**
               * 分別讀純文本和鏈接.
               * 
          @param result 網頁的內容
               * 
          @throws Exception
               
          */

              
          public static void readTextAndLinkAndTitle(String result) throws Exception {
                  Parser parser;
                  NodeList nodelist;
                  parser 
          = Parser.createParser(result, "utf8");
                  NodeFilter textFilter 
          = new NodeClassFilter(TextNode.class);
                  NodeFilter linkFilter 
          = new NodeClassFilter(LinkTag.class);
                  NodeFilter titleFilter 
          = new NodeClassFilter(TitleTag.class);
                  OrFilter lastFilter 
          = new OrFilter();
                  lastFilter.setPredicates(
          new NodeFilter[] { textFilter, linkFilter, titleFilter });
                  nodelist 
          = parser.parse(lastFilter);
                  Node[] nodes 
          = nodelist.toNodeArray();
                  String line 
          = "";
                  
                  
          for (int i = 0; i < nodes.length; i++{
                      Node node 
          = nodes[i];
                      
          if (node instanceof TextNode) {
                          TextNode textnode 
          = (TextNode) node;
                          line 
          = textnode.getText();
                      }
           else if (node instanceof LinkTag) {
                          LinkTag link 
          = (LinkTag) node;
                          line 
          = link.getLink();
                      }
           else if (node instanceof TitleTag) {
                          TitleTag titlenode 
          = (TitleTag) node;
                          line 
          = titlenode.getTitle();
                      }

                      
                      
          if (isTrimEmpty(line))
                          
          continue;
                      System.out.println(line);
                  }

              }

              
              
          /**
               * 去掉左右空格后字符串是否為空
               
          */

              
          public static boolean isTrimEmpty(String astr) {
                  
          if ((null == astr) || (astr.length() == 0)) {
                      
          return true;
                  }

                  
          if (isBlank(astr.trim())) {
                      
          return true;
                  }

                  
          return false;
              }


              
          /**
               * 字符串是否為空:null或者長度為0.
               
          */

              
          public static boolean isBlank(String astr) {
                  
          if ((null == astr) || (astr.length() == 0)) {
                      
          return true;
                  }
           else {
                      
          return false;
                  }

              }

          }


          posted on 2008-01-18 14:18 阿蜜果 閱讀(14597) 評論(2)  編輯  收藏 所屬分類: Java


          FeedBack:
          # re: HTMLParser的使用
          2008-04-17 18:20 | zzz
          請問一下,怎樣將修改過得html保存到文件中
          code如下
          parser = new Parser(getContentByLocalFile(file));
          NodeFilter nt = new NodeClassFilter(ImageTag.class) ;
          NodeList tmpImageList = (NodeList) parser.parse(nt);

          /*linkTmpHash = new Hashtable();
          for (int i = 0; i < length; i++) {
          Element tmpElement = (Element) tmpNodeList.item(i);
          String href = tmpElement.getAttribute("href");
          if (href != null && !href.equals("")) {
          linkTmpHash.put(href, "");
          }
          }
          data.setHrefs((String[]) linkTmpHash.keySet().toArray(new String[linkTmpHash.size()]));*/
          BufferedWriter writer = new BufferedWriter(new OutputStreamWriter (new FileOutputStream (file)));
          linkTmpHash = new Hashtable();
          for (int i = 0; i < tmpImageList.size(); i++) {
          imgnode = (ImageTag)tmpImageList.elementAt(i);
          String src = imgnode.getImageURL();
          if (URLPathNameUtil.isAbsolutePath(src)) {
          if (testAbsolutePath) {
          testImagetag(file,src);
          }
          } else {
          if (testRelativePath) {
          testImagetag(file, src);
          }
          }
          if(getRealPath()!=null){
          imgnode.setImageURL(getRealPath());
          writer.write(tmpImageList.toHtml());
          }
          /*if (src != null && !src.equals("")) {
          linkTmpHash.put(src, "");
          }*/
          }
          writer.flush();
          writer.close ();

          謝謝了  回復  更多評論
            
          # re: HTMLParser的使用
          2009-03-02 13:20 | 黃金礦工
          感覺效率有點低下,另外處理字符編碼的地方有點問題,取正文的時候js代碼去不干凈  回復  更多評論
            
          <2008年1月>
          303112345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

                生活將我們磨圓,是為了讓我們滾得更遠——“圓”來如此。
                我的作品:
                玩轉Axure RP  (2015年12月出版)
                

                Power Designer系統分析與建模實戰  (2015年7月出版)
                
               Struts2+Hibernate3+Spring2   (2010年5月出版)
               

          留言簿(263)

          隨筆分類

          隨筆檔案

          文章分類

          相冊

          關注blog

          積分與排名

          • 積分 - 2296367
          • 排名 - 3

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 关岭| 陆河县| 绥德县| 临西县| 昌宁县| 阳信县| 庄河市| 曲靖市| 鹿泉市| 金昌市| 辛集市| 马鞍山市| 莲花县| 邛崃市| 靖州| 海盐县| 普陀区| 泰宁县| 建湖县| 永泰县| 本溪| 临夏市| 西林县| 神农架林区| 韩城市| 兰考县| 阜南县| 武邑县| 江达县| 汝城县| 泌阳县| 迁安市| 东明县| 万全县| 雷州市| 理塘县| 滦平县| 河曲县| 新巴尔虎右旗| 阿图什市| 安平县|