之前做页面抓取,数据采集等功能的时候,第一个想到的就是用正则表达式去匹配页面内容。但是对于像我这种,正则只懂皮毛的人来说,写正则是真的很恶心的一件事。去网上找,也不一定能改成自己需要的正则。
今天给大家推荐一个很好用的工具smiple html dom。
文档地址:http://www.phpddt.com/manual/simplehtmldom_1_5/manual.htm
解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找定位;同时还提供添加、删除、修改文档树的功能。当然,这样一款强大的html Dom解析器也不是尽善尽美;在使用的过程中需要十分小心内存消耗的情况。不过,不要担心;本文中,笔者在最后会为各位介绍如何避免消耗过多的内存。
下面是我解析的mm131.com的页面内容代码,主要是盗链他的图片,O(∩_∩)O哈哈~
index.php
<meta charset="utf-8"> <form method="post"> <input type="text" style="width:500px;" placeholder="http路径地址,不带.html" name="url" /> <input type="submit" name="提交" value="提交"/> </form> <div id="content">
require './dom/simple_html_dom.php'; require './include/function.php'; //打开错误信息 error_reporting(E_ERROR | E_WARNING | E_PARSE); $count = 0; error_reporting(0); $url = trim(post("url")); $str = ''; if($url){ $html = new simple_html_dom(); $html->load_file($url.'.html'); $ret = $html->find('.content-pic img'); $title = $html->find("title",0); echo str_ireplace("www.mm131.com","",iconv("GBK","UTF-8",$title->innertext))."<br /><br />"; foreach($ret as $v){ if($v->src){ $str .= $v->src."\n"; $count++; } } flush(); for($i = 2;$i < 60;$i++){ $html->clear(); $location = $url.'_'.$i.'.html'; if(!GetCurl($location)){ break; } $html->load_file($location); $ret = $html->find('.content-pic img'); foreach($ret as $v){ if($v->src){ $str .= $v->src."\n"; $count++; } } flush(); } echo $count; }
</div> <textarea style="width:500px;height:500px;"><?php echo $str;?></textarea>
以上3个代码块都是index.php的内容。
其中的require './dom/simple_html_dom.php'; 即引用的simple html dom 解析器。
下载地址:https://github.com/samacs/simple_html_dom
function.php 只是封装了2个方法 代码如下:
function GetCurl($url){ $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY,true); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true); curl_setopt($ch, CURLOPT_AUTOREFERER,true); curl_setopt($ch, CURLOPT_TIMEOUT,30); $rtn = curl_exec($ch); curl_exec($ch); if(strpos($rtn,'404 Not Found')==true) { return false; } return true; } function post($id) { return isset ( $_POST [$id] ) ? $_POST [$id] : ''; }
如何避免解析器消耗过多内存
在本文的开篇中,笔者就提到了Simple HTML DOM解析器消耗内存过多的问题。如果php脚本占用内存太多,会导致网站停止响应等一系列严重的问题。解决的方法也很简单,在解析器加载html文档并使用完成后,记得清理掉这个对象就可以了。当然,也不要把问题看得太严重了。如果只是加载了2、3个文档,清理或不清理是没有多大区别的。当你加载了5个10个甚至更多的文档的时候,用完一个就清理一下内存绝对是对自己负责啦^_^