半自动化之单机爬虫

这篇博文将介绍一下我的这个单机爬虫作品,主要是给大家一个思路,如何做出一个比较有趣的单机爬虫,当然这个作品肯定会有很多改进的地方,欢迎大家提出建议一起改进

   

  爬虫简介:

在部门做爬虫需求的时候,每次来一个需求就需要写一个爬虫程序然后打包部署到服务器,制定脚本定时运行,所以有了这个爬虫,目的是为了尽可能简化现有的流程,之前从网页源码获取,到网页解析,到持久化都需要重新在程序里面重新写一遍,分析了这个过程,我们抽取出了网页源码获取,持久化成为两个独立的类实现原有程序的解耦,然后剩下的也就是我们每次必须要自己手写的网页解析函数(这个过程是必不可少的,因为不同网页需要制定不同的解析规则),从而实现了每次爬虫需求只需要完成网页解析函数,就可以进行打包部署。另外这个爬虫最大的特点就是参数传递和动态加载功能,可以通过传递给程序的参数控制http请求获取网页源码的线程数,加快爬取效率,也可以通过参数控制持久化的方式(文件,数据库),提高程序的复用性。动态加载的功能是用来通过参数来运行对应的Spider实例,实现只需要服务器上部署一个脚本,以后新的需求来了只需要调用同一个脚本传递不同的参数就能运行对应的spider实例。关于多线程爬取返回网页源码的问题,因为不可能等待所有的线程爬取完后网页源码才返回给主线程解析,一是数据量大时内存可能会溢出,而是主线程会一直阻塞,效率太低,主线程采用了一个阻塞队列来达到一个非阻塞的效果,主线程会不断轮询这个阻塞队列,爬虫会不断往阻塞队列里面添加网页源码,主线程检测到队列连续10s为空则结束轮询。

 

关于代码的关键部分和说明我将在下面给出:

项目结构图如下:

                            

common包:

SpiderTemple类: 所有爬虫实例的父类,规定了爬虫实例的入口函数run,规定爬虫实例需要实现的函数parseHtml

[java]  view plain  copy
  1. public class SpiderTemple {  
  2.     protected Persistence persistence = new Persistence();  
  3.     protected HttpRequest httpRequest = new HttpRequest();  
  4.   
  5.     public void run(Map<String, String> map) throws Exception {  
  6.         LinkedBlockingQueue<String> contents = new LinkedBlockingQueue<String>();  
  7.         httpRequest.getContent(contents, map);  
  8.            
  9.          while(true){  
  10.              String poll = contents.poll(5L, TimeUnit.SECONDS);  
  11.              if(null!=poll){  
  12.              System.err.println("poll获取成功,解析后"+parseHtml(poll));  
  13.              persistence.save(map, parseHtml(poll) );  
  14.              }  
  15.              else{  
  16.              System.out.println("队列中无待解析内容");  
  17.              break ;  
  18.              }  
  19.             }  
  20.         }  
  21.       
  22.     public String parseHtml(String url) throws Exception {  
  23.         return null;  
  24.     }  
  25. }  


factory包:

factory类: 根据参数里的类名动态加载不同的爬虫实例进行调用

[java]  view plain  copy
  1. /** 
  2.   * @author: by huizhong 
  3.   * @date: 2016-9-3 上午11:07:14 
  4.   */  
  5.       
  6. public class Factory {  
  7.       
  8.     private static URLClassLoader load;  
  9.   
  10.     /** 
  11.      *  
  12.      * @param className 执行的类名 
  13.      * @param args 类所需要的参数  
  14.      */  
  15.     private void loadClass(String className,Map<String,String> args){  
  16.         String currClasssPath = System.getProperty("java.class.path");  
  17.         String sepStr = System.getProperty("path.separator");  
  18.         String currClassPaths[] = currClasssPath.split(sepStr);  
  19.           
  20.         String libPath = ""//lib文件路径  
  21.           
  22.         for ( int i = 0; i < currClassPaths.length; i++){  
  23.             if( currClassPaths[i].indexOf("Factory") >= 0 && currClassPaths[i].indexOf(".jar") > 0 ){  
  24. //              System.out.print(currClassPaths[i]);  
  25.                 libPath = currClassPaths[i].substring(0,currClassPaths[i].lastIndexOf("/"));  
  26. //              System.out.print(libPath);  
  27.             }  
  28.         }  
  29.           
  30.         if ( libPath.equals("")){  
  31.             libPath = ".";  
  32.         }  
  33.           
  34.         File lib = new File(libPath + "/lib" );  
  35.         File curr = new File(libPath);  
  36.           
  37.         File[] liblist = lib.listFiles(new FilenameFilter() {  
  38.           
  39.             public boolean accept(File dir, String name) {  
  40.                 boolean fileaccept = false;  
  41.                 if (name.endsWith("zip") || name.endsWith("jar")) {  
  42.                     fileaccept = true;  
  43.                 }  
  44.                 return fileaccept;  
  45.             }  
  46.         });  
  47.         //check jar file  
  48.         if(liblist == null || liblist.length < 0 ){  
  49.                  System.out.print("Can not find jar file!");  
  50.             System.exit(1);  
  51.         }  
  52.         URL tmp[] = new URL[liblist.length + 1];  
  53.         String classPathSeparator = System.getProperty("path.separator");  
  54.         StringBuffer buffLib = new StringBuffer();  
  55.         String path = null;  
  56.         try {  
  57.             for (int i = 0; i < liblist.length + 1; i++) {  
  58.                 if (i < liblist.length) {  
  59.                     path = liblist[i].getAbsolutePath();  
  60.                 } else {  
  61.                     path = curr.getAbsolutePath();  
  62.                 }  
  63.                 tmp[i] = new URL("file:/" + path);  
  64.                 buffLib.append(path + ";");  
  65.             }  
  66.             tmp[tmp.length - 1] = new URL("file:/" + path);  
  67.             String paths = System.getProperty("java.class.path") + classPathSeparator  
  68.                     + buffLib.toString();  
  69. //          System.out.print("ClassPath : " + paths);  
  70.             System.setProperty("java.class.path",paths);  
  71.               
  72.                       
  73.             load = new URLClassLoader(tmp, this.getClass().getClassLoader());  
  74.         } catch (MalformedURLException e) {  
  75.             System.out.print(e.toString());  
  76.         }  
  77.         Thread.currentThread().setContextClassLoader(load);  
  78.         Class<?> tmp2;  
  79.         try {  
  80. //          System.out.print(System.getProperty("user.dir"));  
  81.             tmp2 = load.loadClass(className);  
  82.             Object obj = tmp2.newInstance();  
  83.             Method m1 = tmp2.getMethod("run",Map.class);  
  84.             m1.invoke(obj,args);  
  85.         } catch ( ClassNotFoundException e) {  
  86.             System.out.print(e.toString());  
  87.         } catch (InstantiationException e) {  
  88.             System.out.print(e.toString());  
  89.         } catch (IllegalAccessException e) {  
  90.             System.out.print(e.toString());  
  91.         } catch (SecurityException e) {  
  92.             System.out.print(e.toString());  
  93.         } catch (NoSuchMethodException e) {  
  94.             System.out.print(e.toString());  
  95.         } catch (IllegalArgumentException e) {  
  96.             System.out.print(e.toString());  
  97.         } catch (InvocationTargetException e) {  
  98.             System.out.print(e.toString());  
  99.         }  
  100.     }  
  101.       
  102.     public static OptionBuilder inputOption(String descrip,boolean require){    
  103.             OptionBuilder.isRequired(require);  
  104.             OptionBuilder.hasArg();  
  105.         return OptionBuilder.withDescription(descrip);    
  106.         }   
  107.       
  108.     /** 
  109.      * 获取输入的参数 
  110.      * @return CommandLine 
  111.      */  
  112.     private CommandLine getInputArgs(String args[]){  
  113.           
  114.         Options opts = new Options();    
  115.         opts.addOption("h""help"false"print help for the command.");  
  116.         opts.addOption(Factory.inputOption("input className。 eg com.heme.taobaoSSQ",true).create("className"));  
  117.         opts.addOption(Factory.inputOption("className require args. eg uri,saveType[,savePath,threadNum]",false).create("arg"));    
  118.           
  119.         BasicParser parser = new BasicParser();    
  120.         String format_str = "java com.heme.httpWatch.httpRobot -className com.heme.** -arg ***";   
  121.         HelpFormatter formatter = new HelpFormatter();  
  122.         CommandLine cl = null;    
  123.         try{    
  124.               
  125.             System.err.println("开始解析参数");  
  126.               
  127.             cl = parser.parse(opts, args);  
  128.             if (cl.hasOption("h")){  
  129.                 formatter.printHelp(format_str, opts);  
  130.             }  
  131.         }catch (ParseException e) {  
  132.               
  133.             System.err.println("解析出错");  
  134.               
  135.             formatter.printHelp(format_str, opts);  
  136.             System.exit(1);  
  137.         }  
  138.           
  139.         return cl;  
  140.     }  
  141.       
  142.     public static void main(String args[]) {  
  143.           
  144.         Factory hr = new Factory();  
  145.         CommandLine cl = hr.getInputArgs(args);  
  146.           
  147.         String className    = cl.getOptionValue("className"); //要执行的类  
  148.         String classNameArg = cl.getOptionValue("arg"); //类所需要的参数  
  149.           
  150.         Map<String,String> map = new HashMap<String,String>();  
  151.         if( classNameArg != null && !"".equals(classNameArg) ){  
  152.             String[] classNameArgs = classNameArg.split(",");  
  153.             forint i = 0; i < classNameArgs.length; i++ ){  
  154.                 String[] darg = classNameArgs[i].split("=");  
  155.                 if ( darg.length == 2 ){  
  156.                     map.put(darg[0], darg[1]);  
  157.                 }else{  
  158.                     int pivot = classNameArgs[i].indexOf("=");  
  159.                     map.put(classNameArgs[i].substring(0, pivot),classNameArgs[i].substring(pivot+1));  
  160.                 }  
  161.             }  
  162.         }  
  163.         hr.loadClass(className,map);  
  164.     }  
  165.       
  166. }  

Rquest包:

httpRequest类:发送http请求获取网页源码,根据传递进来的参数决定是爬取一个url还是爬取文件里的一系列url

[java]  view plain  copy
  1. public class HttpRequest {  
  2.     protected HttpUtil httpUtil = new HttpUtil();  
  3.     protected ExecutorService executor = Executors.newFixedThreadPool(50); // 创建固定容量大小的缓冲池  
  4.     List<String> contents = new LinkedList<String>();  
  5.       
  6.     public void getContent(final LinkedBlockingQueue<String> contents,  
  7.             final Map<String, String> map) throws Exception {  
  8.       
  9.         String uri = map.get("uri");  
  10.     if (null != uri && uri.contains("http")) { // uri代表网址  
  11.         try {  
  12.         String content = httpUtil.getUrlAsString(uri);  
  13.         System.err.println("add content");  
  14.         contents.add(content);  
  15.         } catch (Exception e) {  
  16.         System.err.println("爬起url出错,请检查网络问题");  
  17.         }  
  18.     }  
  19.   
  20.     else if (null != uri && !uri.contains("http")) { // uri代表文件  
  21.         final List<String> urlList = new ArrayList<String>();  
  22.         BufferedReader bufferedReader = new BufferedReader(new FileReader(uri));  
  23.         String name = null;  
  24.         while ((name = bufferedReader.readLine()) != null) {  
  25.         urlList.add(name);  
  26.         }  
  27.   
  28.         new Thread(new Runnable() { // 默认开启一个线程  
  29.             @Override  
  30.             public void run() {  
  31.                 // TODO Auto-generated method stub  
  32.                 for (final String url : urlList) {  
  33.                 if (null == map.get("thread")) {  
  34.                     try {  
  35.                     String content = httpUtil.getUrlAsString("http://" + url);  
  36.                     contents.add(content);  
  37.                     } catch (Exception e) {  
  38.                     System.err.println("爬起url出错,请检查网络问题");  
  39.                     }  
  40.   
  41.                 } else if ("true".equals(map.get("thread"))) {  
  42.                     // 针对每个Ur均开启一个线程进行爬取  
  43.                     executor.execute(new Runnable() { // 缓冲池最多开启50个线程  
  44.                     @Override  
  45.                     public void run() {                      
  46.                         String content;  
  47.                         try {  
  48.                         System.out.println(Thread.currentThread()+" is running");  
  49.                         content = httpUtil.getUrlAsString("http://"+ url);  
  50.                         contents.add(content);  
  51.                         } catch (Exception e) {  
  52.                         e.printStackTrace();  
  53.                         }  
  54.                     }  
  55.                     });  
  56.   
  57.                 }  
  58.                 }  
  59.             }  
  60.             }).start();  
  61.     }  
  62.     }  
  63. }  
Spiders包:

SpiderDemo类:为Spider实例提供一个Demo,以后的Spider实例只需要按这个规范写即可以,

[java]  view plain  copy
  1. public class SpiderDemo extends SpiderTemple implements Entrance {  
  2.   
  3.      
  4.   
  5.     @Override  
  6.     public String parseHtml(String content) throws Exception {  
  7.   
  8.     Document doc = Jsoup.parse(content);  
  9.     String title = doc.select("meta[name=Description]").attr("content");  
  10.     String time = doc.select("span[class=pubTime article-time]").text();  
  11.     String comment = doc.select("a[id=cmtNum]").text();  
  12.     String text = doc.select("div[id=Cnt-Main-Article-QQ] span").text()  
  13.         + doc.select("div[id=Cnt-Main-Article-QQ] p").text();  
  14.   
  15.     // 这里要和数据库除了主键以外的字段数目一致,字段分隔符&&&  
  16.     return title + time + comment + text;  
  17.     }  
  18.   
  19. }  
Util包:

一些用于发送http请求,落地到文件或者db的工具


这个爬虫可以改进的地方还有很多,比如一些应对反爬措施等等,但是结合业务需求来看暂时是没必要做的,有句话说得好,“如无必要,勿增实体”,一些应对反爬措施我也会在后面的分布式爬虫提到,大家可以去参考一下

如果大家有什么好的改进建议和疑问可以给我留言或者给我邮件,一起改进这个爬虫~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值