使用HtmlParser读取论坛图片

来源:互联网 发布:阿里云域名备案成功后 编辑:程序博客网 时间:2024/05/16 15:39

 心血来潮,写了一个读取论坛图片的程序,能够自动把图片保存到硬盘上去,使用HtmlParse组件。

http://hintcnuie.javaeye.com/blog/172132

 

  1. package com.chen;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.File;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.MalformedURLException;  
  9. import java.net.URL;  
  10. import java.util.HashSet;  
  11. import java.util.Set;  
  12.   
  13. import org.htmlparser.NodeFilter;  
  14. import org.htmlparser.Parser;  
  15. import org.htmlparser.filters.TagNameFilter;  
  16. import org.htmlparser.tags.ImageTag;  
  17. import org.htmlparser.tags.LinkTag;  
  18. import org.htmlparser.tags.TitleTag;  
  19. import org.htmlparser.util.NodeList;  
  20. import org.htmlparser.util.ParserException;  
  21.   
  22. /  
  23. public class HttpGet {  
  24.   
  25.     private static int BUFFER_SIZE = 8096;// 缓冲区大小  
  26.   
  27.     /** 
  28.      * 将HTTP资源另存为文件 
  29.      *  
  30.      * @param destUrl 
  31.      *            String 
  32.      * @param title 
  33.      * @param fileName 
  34.      *            String 
  35.      * @throws IOException 
  36.      * @throws Exception 
  37.      */  
  38.     public static void saveToFile(String destUrl, String title) {  
  39.         FileOutputStream fos = null;  
  40.         BufferedInputStream bis = null;  
  41.         HttpURLConnection httpUrl = null;  
  42.         URL url = null;  
  43.         byte[] buf = new byte[BUFFER_SIZE];  
  44.         int size = 0;  
  45.         int pos = destUrl.lastIndexOf('/');  
  46.   
  47.         String fileName = "";  
  48.         if (pos != -1)  
  49.             fileName = destUrl.substring(pos + 1, destUrl.length());  
  50.         else  
  51.             fileName = destUrl.substring(destUrl.length() - 10, destUrl  
  52.                     .length());  
  53.         String path = "D:" + File.separator + "temp" + File.separator  
  54.                 + "images" + File.separator;  
  55.   
  56.         System.out.println("title: " + title);  
  57.   
  58.         if (null != title && !"".equals(title)) {  
  59.             File file = new File(path + title + File.separator);  
  60.             if (!file.exists()) {  
  61.                 file.mkdirs();  
  62.   
  63.             }  
  64.           
  65.             path = file.getPath();  
  66.         }  
  67.         path = path + File.separator + fileName;  
  68.         System.out.print("/t" + path);  
  69.         // 建立链接  
  70.         try {  
  71.             url = new URL(destUrl);  
  72.             httpUrl = (HttpURLConnection) url.openConnection();  
  73.             // 连接指定的资源  
  74.             httpUrl.connect();  
  75.             // 获取网络输入流  
  76.             bis = new BufferedInputStream(httpUrl.getInputStream());  
  77.             // 建立文件  
  78.   
  79.             fos = new FileOutputStream(path);  
  80.   
  81.             // 保存文件  
  82.             while ((size = bis.read(buf)) != -1)  
  83.                 fos.write(buf, 0, size);  
  84.   
  85.             fos.close();  
  86.             bis.close();  
  87.             httpUrl.disconnect();  
  88.         } catch (MalformedURLException e) {  
  89.             // TODO Auto-generated catch block  
  90.             e.printStackTrace();  
  91.         } catch (IOException ex) {  
  92.             // TODO Auto-generated catch block  
  93.             ex.printStackTrace();  
  94.         }  
  95.         System.out.println(" /tsave completely");  
  96.     }  
  97.   
  98.     /** 
  99.      * 主方法 
  100.      *  
  101.      * @param argv 
  102.      *            String[] 
  103.      */  
  104.     public static void main(String argv[]) {  
  105.   
  106.         String url = "http://xxx.com";  
  107.           
  108.         // getImagesFromSinglePage(url);  
  109.         try {  
  110.               
  111.             String page = null;  
  112.             for(int i=2;i<=105;i++){  
  113.                 page="http://xx.com/html/13/13_"+i+".shtml";  
  114.                 getPageLinks(page);  
  115.             }  
  116.             getPageLinks(url);  
  117.             // String title=getTitle(url);  
  118.             // getImages(url,title);  
  119.         } catch (Exception e) {  
  120.             // TODO Auto-generated catch block  
  121.             e.printStackTrace();  
  122.         }  
  123.         // getImagesByParser(url);  
  124.   
  125.     }  
  126.   
  127.     private static void getPageLinks(String page) throws ParserException {  
  128.   
  129.         Parser myParser = new Parser(page);  
  130.   
  131.         // 设置编码  
  132.         myParser.setEncoding("UTF-8");  
  133.         String filterStr = "a";  
  134.         NodeFilter filter = new TagNameFilter(filterStr);  
  135.         NodeList nodeList = myParser.extractAllNodesThatMatch(filter);  
  136.         System.out.println("size: " + nodeList.size());  
  137.   
  138.         for (int i = 0; i < nodeList.size(); i++) {  
  139.             LinkTag linkTag = (LinkTag) nodeList.elementAt(i);  
  140.             String link = linkTag.getLink();  
  141.             String text = linkTag.getLinkText();  
  142.             text = TextProcess(text);  
  143.             if (link.endsWith(".shtml") && text.length() > 2) {  
  144.                 try {  
  145.                     getImages(link,text);  
  146.                 } catch (Exception e) {  
  147.                     // TODO Auto-generated catch block  
  148.                     e.printStackTrace();  
  149.                 }  
  150.             }  
  151.         }  
  152.   
  153.     }  
  154.   
  155.     private static String TextProcess(String text) {  
  156.         text = text.trim();  
  157.         text = text.replaceAll(">""");  
  158.         text = text.replaceAll("<""");  
  159.         text = text.replaceAll("/""");  
  160.         text = text.replaceAll(">""");  
  161.         text = text.replaceAll(" """);  
  162.         int pos = 0;  
  163.         if ((pos = text.indexOf(":-")) != -1)  
  164.             text = text.substring(pos + 2);  
  165.   
  166.         pos = text.indexOf("-");  
  167.         if (pos != -1)  
  168.             text = text.substring(0, pos);  
  169.         pos = text.indexOf("-");  
  170.         if (pos != -1)  
  171.             text = text.substring(0, pos);  
  172.         text = text.replace(".""");  
  173.         text = text.replaceAll(",""");  
  174.         text = text.replaceAll(",""");  
  175.         return text;  
  176.     }  
  177.   
  178.     private static String getTitle(String url) throws ParserException {  
  179.   
  180.         Parser myParser = new Parser(url);  
  181.   
  182.         // 设置编码  
  183.         myParser.setEncoding("UTF-8");  
  184.   
  185.         String titleTag = "title";  
  186.         NodeFilter titleFilter = new TagNameFilter(titleTag);  
  187.         NodeList titleList = myParser.extractAllNodesThatMatch(titleFilter);  
  188.         int size = titleList.size();  
  189.         String title = null;  
  190.         if (size == 1) {  
  191.             TitleTag titleT = (TitleTag) titleList.elementAt(0);  
  192.             title = titleT.getTitle();  
  193.   
  194.         }  
  195.         return title;  
  196.   
  197.     }  
  198.   
  199.     public static void getImages(String resource, String title)  
  200.             throws Exception {  
  201.   
  202.         // Set  
  203.         Set<String> imagesSet = new HashSet<String>();  
  204.         Parser myParser = new Parser(resource);  
  205.   
  206.         // 设置编码  
  207.         myParser.setEncoding("UTF-8");  
  208.         String filterStr = "img";  
  209.         NodeFilter filter = new TagNameFilter(filterStr);  
  210.         NodeList nodeList = myParser.extractAllNodesThatMatch(filter);  
  211.         System.out.println("size: " + nodeList.size());  
  212.   
  213.         for (int i = 0; i < nodeList.size(); i++) {  
  214.             ImageTag imageTag = (ImageTag) nodeList.elementAt(i);  
  215.             String imageUrl = imageTag.getImageURL();  
  216.             System.out.println("iamge " + i + ": " + imageUrl);  
  217.             if (!imagesSet.contains(imageUrl)) {  
  218.                 System.out.print("/t saving ...");  
  219.                 saveToFile(imageTag.getImageURL(), title);  
  220.             } else {  
  221.                 System.out.print("/t exist already,no need to save");  
  222.             }  
  223.         }  
  224.   
  225.     }  
  226.   
  227. }

 

原创粉丝点击