免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1732 | 回复: 1
打印 上一主题 下一主题

php实现的web采集神器 [复制链接]

论坛徽章:
1
程序设计版块每日发帖之星
日期:2015-07-10 22:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-09 11:14 |只看该作者 |倒序浏览
php实现的web采集神器,只需要通过简单配置,就可以采集任意没有严格校验的站点
可以扩展IP代理功能以及伪原创功能

[PHP]代码
  1. <?php
  2. /**
  3. *  可以灵活配置使用的采集器
  4. *  作者:Rain
  5. *  创建时间:2015-02-03 15:17:30
  6. *  版本信息:V1.0
  7. */

  8. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  9. //数据库的相关配置信息,请根据您的数据库信息进行配置
  10. define('DB_HOST', 'localhost');
  11. define('DB_USER', 'root');
  12. define('DB_PWD', 'test123456');
  13. define('DB_NAME', 'test_dbname');
  14. define('DB_CHARSET', 'utf8');
  15. define('TABLE_NAME', 'tb_book');
  16. //end

  17. //网站信息相关的配置,请根据具体需要采集的网站内容信息进行配置
  18. define('WEB_CHARSET', 'gbk');
  19. //变动的参数,使用%d进行替换,只支持数值形式的变动
  20. define('WEB_LIST_URL', 'http://www.pcbookcn.com/book/1_%d.htm');
  21. //分页的条数
  22. define('PAGE_COUNT', 14);
  23. //从哪个页面开始抓取
  24. define('PAGE_START', 1);
  25. //内容页的URL,使用正则模式,必须包含/,例如:/\/xuefu2008\/article\/details\/(\d)+/i
  26. define('WEB_CONTENT_URL_REG', '/\/book\/(\d)+\.htm/i');
  27. //网站域名HOST信息,不包含末尾的/,例如:http://blog.csdn.net
  28. define('WEB_HOST', 'http://www.pcbookcn.com');
  29. //列表页内容的精准定位,用来大致抓取一个列表页的内容显示模块位置,使用正则进行定位
  30. define('WEB_LIST_POSTION', '/book_name\.gif(.*?)<td\swidth="15\%"\snowrap>/i');
  31. //end

  32. //微调参数,通常不修改也不会影响您的正常使用
  33. define('SLEEP_TIME', 1);
  34. define('IS_DEBUG', false);
  35. define('INSERT_DB', true);
  36. //内容的输出速度,单位:秒
  37. define('OUTPUT_SPEED', 1);
  38. //end

  39. //需要过滤删除的文字,根据采集的网站类型进行设置,不区分大小写
  40. $text_filter = array(
  41.     '- 中华电脑书库' => '',
  42.     '_电脑电子书' => '',
  43.     '_电脑书籍' => '',
  44.     '下载' => '',
  45. );

  46. //表结构映射的配置
  47. $table_mapping = array(
  48. //表字段名称 => 获取该字段的正则表达式,非空字段都必须在此设置映射关系,常量值请直接填写具体对应的值,无需使用正则
  49.     'size' => '/软件大小.*?000000>(.*?)<\/font>/i',
  50.     'logo' => 'http://www.94cto.com/index/uploads/images/20150105/0b8461910de101cc51a07684cdab797e.jpg',
  51.     'field1' => '/<title>(.*?)<\/title>/i',
  52.     'field2' => '/软件简介.*?000000>(.*?)<\/font>/i',
  53.     'field3' => '1',
  54.     'field4' => '1',
  55.     'field5' => '1',
  56.     'field6' => '电子书,计算机,图像,图形',
  57.     'platform' => 'window/Linux',
  58.     'ishot' => '1',
  59.     'agreement' => '免费',
  60.     'downurl' => '/(\/down\.asp\?id=.*?)"/i',
  61.     'istop' => '1',
  62. );
  63. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  64. $ga = new Gather();
  65. $ga->run();

  66. class Gather
  67. {
  68.     public function __construct()
  69.     {
  70.         $this->init_check();
  71.     }

  72.     public function run()
  73.     {
  74.         global $table_mapping, $text_filter;

  75.         for ($page = PAGE_START; $page <= PAGE_COUNT; $page++)
  76.         {

  77.             $this->write('开始采集列表第'.$page.'页的内容...');
  78.             $list_content = $this->get(sprintf(WEB_LIST_URL, $page));
  79.             if (empty($list_content))
  80.             {
  81.                 $this->write('抓取的列表页的内容为空,所以过滤掉');
  82.                 continue;
  83.             }

  84.             $list_content = str_replace("\r", '', $list_content);
  85.             $list_content = str_replace("\n", '', $list_content);

  86.             //精准定位要抓取的模块内容
  87.             if (!preg_match(WEB_LIST_POSTION, $list_content, $list_search))
  88.             {
  89.                 $this->write('精准匹配列表页的内容失败,所以过滤掉');
  90.                 continue;
  91.             }
  92.             if (isset($list_search[1]))
  93.                 $list_content = $list_search[1];
  94.             else
  95.                 $list_content = $list_search[0];
  96.             //end

  97.             preg_match_all(WEB_CONTENT_URL_REG, $list_content, $match);
  98.             if (is_array($match[0]) && !empty($match[0]))
  99.             {
  100.                 $this->write('当前的列表页面,总共匹配到:'.count($match[0]).'个内容页');
  101.                 foreach ($match[0] as $val)
  102.                 {
  103.                     if (strpos($val, 'http:') === false)
  104.                     {
  105.                         if (substr($val, 0, 1) == '/')
  106.                             $val = WEB_HOST.$val;
  107.                         else
  108.                             $val = WEB_HOST.'/'.$val;
  109.                     }
  110.                     $web_content = $this->get($val);
  111.                     if (empty($web_content))
  112.                     {
  113.                         $this->write('抓取的内容页为空,所以过滤掉');
  114.                         continue;
  115.                     }

  116.                     $web_content = str_replace("\r", '', $web_content);
  117.                     $web_content = str_replace("\n", '【】', $web_content);

  118.                     $sql = "INSERT INTO ".TABLE_NAME."(".implode(', ', array_keys($table_mapping)).")VALUES(";
  119.                     foreach ($table_mapping as $field => $reg)
  120.                         $sql .= ':'.$field.',';
  121.                     $sql = substr($sql ,0, -1);
  122.                     $sql .= ')';

  123.                     if (IS_DEBUG)
  124.                         $this->write('执行SQL '.$sql);

  125.                     $dsn = 'mysql:dbname='.DB_NAME.';host='.DB_HOST;
  126.                     try {
  127.                         $dbh = new PDO($dsn, DB_USER, DB_PWD);
  128.                     } catch (PDOException $e) {
  129.                         $this->write( 'Connection failed: ' . $e->getMessage(), true);
  130.                     }
  131.                     $dbh->query("set names 'utf8'");
  132.                     $sth = $dbh->prepare($sql);

  133.                     foreach ($table_mapping as $field => $reg)
  134.                     {
  135.                         if (substr($reg, 0, 1) !=  '/')
  136.                         {
  137.                             $field = $reg;
  138.                         }
  139.                         else
  140.                         {
  141.                             if (!preg_match($reg, $web_content, $tmp_match))
  142.                             {
  143.                                 $this->write('对不起,匹配字段:'.$field.'失败,过滤此记录');
  144.                                 continue 2;
  145.                             }

  146.                             $field = $tmp_match[1];
  147.                             $field = $this->closetags($field);
  148.                              
  149.                             //删除javascript脚本
  150.                             $field = preg_replace('/<script(.*?)>(.*?)<\/script>/i', '', $field);

  151.                             //将链接删除
  152.                             $field = preg_replace('/<a(.*?)>(.*?)<\/a>/i', '${2}', $field);

  153.                             //图片链接地址绝对地址化
  154.                             preg_match_all('/<img.*?src=("|\')+(.*?)("|\')+.*?>/i', $field, $img_match);
  155.                             if (isset($img_match[2]) && is_array($img_match[2]) && !empty($img_match[2]))
  156.                             {
  157.                                 foreach ($img_match[2] as $img_val)
  158.                                 {
  159.                                     if (strpos($img_val, 'http:') === false)
  160.                                     {
  161.                                         $new_val = $img_val;
  162.                                         if (substr($new_val, 0, 1) != '/')
  163.                                             $new_val = '/'.$img_val;
  164.                                         $new_val = WEB_HOST.$new_val;
  165.                                         $field = str_replace($img_val, $new_val, $field);
  166.                                     }
  167.                                 }
  168.                             }
  169.                             //end

  170.                             //针对HTML里面的pre的换行先做一个特殊处理
  171.                             $field = preg_replace('/<pre.*?>(.*?)<\/pre>/i', '<pre class="prettyprint">${1}</pre>', $field);
  172.                             preg_match_all('/<pre>(.*?)<\/pre>/i', $field, $pre_match);
  173.                             if (isset($pre_match[1]) && is_array($pre_match[1]) && !empty($pre_match[1]))
  174.                             {
  175.                                 foreach ($pre_match[1] as $pre_val)
  176.                                     $field = str_replace($pre_val, str_replace("【】", "\r\n", $pre_val), $field);
  177.                             }
  178.                             //end
  179.                         }

  180.                         //入库之前,将对应的换行符号都还原回来
  181.                         $field = str_replace('【】', "\r\n", $field);
  182.                         //文本的过滤和替换操作
  183.                         if (is_array($text_filter) && !empty($text_filter))
  184.                         {
  185.                             foreach ($text_filter as $tk => $tv)
  186.                                 $field = str_ireplace($tk, $tv, $field);
  187.                         }

  188.                         if (IS_DEBUG)
  189.                             $this->write('*'."\t".'字段:'.$field.'  值:'."\n****************************************************\n".$field."\n****************************************************");
  190.                         if ('downurl' == $field && stripos($field, 'http:') === false)
  191.                             if (substr($field, 0, 1) == '/')
  192.                                 $field = WEB_HOST.trim($field);
  193.                             else
  194.                                 $field = WEB_HOST.'/'.trim($field);
  195.                         $sth->bindValue(':'.$field, trim($field));
  196.                     }
  197.                     if (INSERT_DB)
  198.                         $sth->execute();
  199.                     $sth->closeCursor();

  200.                     $this->write( '休息,暂停'.SLEEP_TIME.'秒后继续抓取...');
  201.                     sleep(SLEEP_TIME);
  202.                 }
  203.             }
  204.             else
  205.             {
  206.                 $this->write('列表页面没有抓取到内容,所以过滤掉');
  207.             }
  208.         }
  209.         $this->write('', true);
  210.     }

  211.     protected function closetags($html)
  212.     {
  213.         // 不需要补全的标签
  214.         $arr_single_tags = array('meta', 'img', 'br', 'link', 'area');
  215.         // 匹配开始标签
  216.         preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
  217.         $openedtags = $result[1];
  218.         // 匹配关闭标签
  219.         preg_match_all('#</([a-z]+)>#iU', $html, $result);
  220.         $closedtags = $result[1];
  221.         // 计算关闭开启标签数量,如果相同就返回html数据
  222.         $len_opened = count($openedtags);
  223.         if (count($closedtags) == $len_opened) {
  224.         return $html;
  225.         }
  226.         // 把排序数组,将最后一个开启的标签放在最前面
  227.         $openedtags = array_reverse($openedtags);
  228.         // 遍历开启标签数组
  229.         for ($i = 0; $i < $len_opened; $i++) {
  230.         // 如果需要补全的标签
  231.         if (!in_array($openedtags[$i], $arr_single_tags)) {
  232.         // 如果这个标签不在关闭的标签中
  233.         if (!in_array($openedtags[$i], $closedtags)) {
  234.         // 直接补全闭合标签
  235.         $html .= '</' . $openedtags[$i] . '>';
  236.         } else {
  237.         unset($closedtags[array_search($openedtags[$i], $closedtags)]);
  238.         }
  239.         }
  240.         }
  241.     return $html;
  242.     }

  243.     protected function init_check()
  244.     {
  245.         if (!$this->check_curl_support())
  246.             $this->write('对不起,请先开启CURL的类库的支持,否则无法执行', true);
  247.         $this->check_mysql_connect();
  248.         $this->write('程序初始化检查通过,执行后续的流程...');
  249.     }

  250.     private function get($url, $data = array())
  251.     {
  252.         $this->write('开始执行抓取: '.$url);
  253.         $ch = curl_init();
  254.         curl_setopt($ch, CURLOPT_URL, $url);
  255.         //curl_setopt($ch, CURLOPT_USERAGENT, "Baiduspider+(+http://www.baidu.com/search/spider.htm)");
  256.         curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
  257.         curl_setopt($ch, CURLOPT_HEADER, 0);
  258.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  259.         curl_setopt($ch, CURLOPT_HTTPHEADER, $data);
  260.         $ret = curl_exec($ch);
  261.         $error = curl_error($ch);
  262.         curl_close($ch);
  263.         unset($ch);
  264.         if (!empty($error))
  265.         {
  266.             $this->write('程序抓取URL: '.$url.'发生错误,错误信息: '.$error);
  267.             return false;
  268.         }
  269.         if (WEB_CHARSET != 'utf-8')
  270.             $ret = iconv(WEB_CHARSET, 'utf-8', $ret);
  271.         return $ret;
  272.     }

  273.     //when check finish,mysql connect will auto close
  274.     private function check_mysql_connect()
  275.     {
  276.         $con = mysql_connect(DB_HOST, DB_USER, DB_PWD);
  277.         if (!is_resource($con))
  278.             $this->write('程序无法成功链接到数据库,具体的错误信息:'.mysql_error(), true);
  279.         if (!mysql_select_db(DB_NAME, $con))
  280.             $this->write('程序无法链接到数据库: '.DB_NAME.',具体的错误信息: '.mysql_error(), true);
  281.         mysql_close($con);
  282.     }

  283.     private function check_curl_support()
  284.     {
  285.         if (!extension_loaded('curl') || !function_exists('curl_init'))
  286.             return false;
  287.         return true;
  288.     }

  289.     private function write($str, $end = false)
  290.     {
  291.         if (PATH_SEPARATOR == ':')
  292.             echo $str,PHP_EOL,PHP_EOL;
  293.         else
  294.             echo iconv('UTF-8', 'GBK', $str),PHP_EOL,PHP_EOL;

  295.         if ($end)
  296.             die("program exit");

  297.         sleep(OUTPUT_SPEED);
  298.     }
  299. }
复制代码

论坛徽章:
59
2015七夕节徽章
日期:2015-08-24 11:17:25ChinaUnix专家徽章
日期:2015-07-20 09:19:30每周论坛发贴之星
日期:2015-07-20 09:19:42ChinaUnix元老
日期:2015-07-20 11:04:38荣誉版主
日期:2015-07-20 11:05:19巳蛇
日期:2015-07-20 11:05:26CU十二周年纪念徽章
日期:2015-07-20 11:05:27IT运维版块每日发帖之星
日期:2015-07-20 11:05:34操作系统版块每日发帖之星
日期:2015-07-20 11:05:36程序设计版块每日发帖之星
日期:2015-07-20 11:05:40数据库技术版块每日发帖之星
日期:2015-07-20 11:05:432015年辞旧岁徽章
日期:2015-07-20 11:05:44
2 [报告]
发表于 2015-07-10 09:53 |只看该作者
这个到底是要采集什么。楼主只贴上代码。为什么不把功能说明白呢。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP