php解析html类库simple_html_dom(爬虫相关)

来源:互联网 发布:软件项目管理课程设计 编辑:程序博客网 时间:2024/06/06 19:26
下载地址:https://github.com/samacs/simple_html_dom

解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找定位;同时还提供添加、删除、修改文档树的功能。当然,这样一款强大的html Dom解析器也不是尽善尽美;在使用的过程中需要十分小心内存消耗的情况。不过,不要担心;本文中,笔者在最后会为各位介绍如何避免消耗过多的内存。
开始使用
上传类文件以后,有三种方式调用这个类:
从url中加载html文档
从字符串中加载html文档
从文件中加载html文档

[html] view plain copy
  1. <?php  
  2. // 新建一个Dom实例  
  3. $html = new simple_html_dom();  
  4.   
  5. // 从url中加载  
  6. $html->load_file('http://www.jb51.net');  
  7.   
  8. // 从字符串中加载  
  9. $html->load('<html><body>从字符串中加载html文档演示</body></html>');  
  10.   
  11. //从文件中加载  
  12. $html->load_file('path/file/test.html');  
  13. ?>  



如果从字符串加载html文档,需要先从网络上下载。建议使用CURL来抓取html文档并加载DOM中。

PHP Simple HTML DOM Parser提供了3种方式来创建DOM对象 :


[html] view plain copy
  1. // Create a DOM object from a string   
  2. $html = str_get_html('<html><body>Hello!</body></html>');   
  3. // Create a DOM object from a URL   
  4. $html = file_get_html('http://www.google.com/');   
  5. // Create a DOM object from a HTML file   
  6. $html = file_get_html('test.htm');   


查找html元素
可以使用find函数来查找html文档中的元素。返回的结果是一个包含了对象的数组。我们使用HTML DOM解析类中的函数来访问这些对象,下面给出几个示例:

[html] view plain copy
  1. <?php  
  2.   
  3. //查找html文档中的超链接元素  
  4. $a = $html->find('a');  
  5.   
  6. //查找文档中第(N)个超链接,如果没有找到则返回空数组.  
  7. $a = $html->find('a', 0);  
  8.   
  9. // 查找id为main的div元素  
  10. $main = $html->find('div[id=main]',0);  
  11.   
  12. // 查找所有包含有id属性的div元素  
  13. $divs = $html->find('div[id]');  
  14.   
  15. // 查找所有包含有id属性的元素  
  16. $divs = $html->find('[id]');  
  17. ?>  



还可以使用类似jQuery的选择器来查找定位元素:

[html] view plain copy
  1. <?php  
  2. // 查找id='#container'的元素  
  3. $ret = $html->find('#container');  
  4.   
  5. // 找到所有class=foo的元素  
  6. $ret = $html->find('.foo');  
  7.   
  8. // 查找多个html标签  
  9. $ret = $html->find('a, img');  

[html] view plain copy
  1. // 还可以这样用  
  2. $ret = $html->find('a[title], img[title]');  
  3. ?>  


解析器支持对子元素的查找

[html] view plain copy
  1. <?php  
  2.   
  3. // 查找 ul列表中所有的li项  
  4. $ret = $html->find('ul li');  
  5.   
  6. //查找 ul 列表指定class=selected的li项  
  7. $ret = $html->find('ul li.selected');  
  8.   
  9. ?>  


如果你觉得这样用起来麻烦,使用内置函数可以轻松定位元素的父元素、子元素与相邻元素

[html] view plain copy
  1. <?php  
  2. // 返回父元素  
  3. $e->parent;  
  4.   
  5. // 返回子元素数组  
  6. $e->children;  
  7.   
  8. // 通过索引号返回指定子元素  
  9. $e->children(0);  
  10.   
  11. // 返回第一个资源速  
  12. $e->first_child ();  
  13.   
  14. // 返回最后一个子元素  
  15. $e->last _child ();  
  16.   
  17. // 返回上一个相邻元素  
  18. $e->prev_sibling ();  
  19.   
  20. //返回下一个相邻元素  
  21. $e->next_sibling ();  
  22. ?>  



元素属性操作
使用简单的正则表达式来操作属性选择器。
[attribute] – 选择包含某属性的html元素
[attribute=value] – 选择所有指定值属性的html元素
[attribute!=value]- 选择所有非指定值属性的html元素
[attribute^=value] -选择所有指定值开头属性的html元素
[attribute$=value] 选择所有指定值结尾属性的html元素
[attribute*=value] -选择所有包含指定值属性的html元素
在解析器中调用元素属性
在DOM中元素属性也是对象:
[html] view plain copy
  1. <?php  
  2. // 本例中将$a的锚链接值赋给$link变量  
  3. $link = $a->href;  
  4. ?>  

或者:

[html] view plain copy
  1. <?php  
  2. $link = $html->find('a',0)->href;  
  3. ?  


每个对象都有4个基本对象属性:
tag – 返回html标签名
innertext – 返回innerHTML
outertext – 返回outerHTML
plaintext – 返回html标签中的文本
在解析器中编辑元素
编辑元素属性的用法和调用它们是类似的:
[html] view plain copy
  1. <?php  
  2. //给$a的锚链接赋新值  
  3. $a->href = 'http://www.jb51.net';  
  4.   
  5. // 删除锚链接  
  6. $a->href = null;  
  7.   
  8. // 检测是否存在锚链接  
  9. if(isset($a->href)) {  
  10. //代码  
  11. }  
  12. ?>  


解析器中没有专门的方法来添加、删除元素,不过可以变通一下使用:

[html] view plain copy
  1. <?php  
  2. // 封装元素  
  3. $e->outertext = '<div class="wrap">' . $e->outertext . '<div>';  
  4.   
  5. // 删除元素  
  6. $e->outertext = '';  
  7.   
  8. // 添加元素  
  9. $e->outertext = $e->outertext . '<div>foo<div>';  
  10.   
  11. // 插入元素  
  12. $e->outertext = '<div>foo<div>' . $e->outertext;  
  13. ?>  



保存修改后的html DOM文档也非常简单:
[html] view plain copy
  1. <?php  
  2. $doc = $html;  
  3. // 输出  
  4. echo $doc;  
  5. ?>  



如何避免解析器消耗过多内存
在本文的开篇中,笔者就提到了Simple HTML DOM解析器消耗内存过多的问题。如果php脚本占用内存太多,会导致网站停止响应等一系列严重的问题。解决的方法也很简单,在解析器加载html文档并使用完成后,记得清理掉这个对象就可以了。当然,也不要把问题看得太严重了。如果只是加载了2、3个文档,清理或不清理是没有多大区别的。当你加载了5个10个甚至更多的文档的时候,用完一个就清理一下内存

[html] view plain copy
  1. <?php  
  2. $html->clear();  
  3. ?>  


一个实例:

[html] view plain copy
  1. <p>简单范例    
  2. <?PHP  
  3.     include "simple_html_dom.php" ;//加载simple_html_dom.php文件    
  4.     $html = file_get_html('http://www.google.com/');//获取html                              
  5.     $dom = new simple_html_dom(); //new simple_html_dom对象                              
  6.     $dom->load($html)  //加载html                                              
  7.     // Find all images                                            
  8.     foreach($dom->find('img') as $element) {     
  9.     //获取img标签数组                                        
  10.         echo $element->src . '<br>'; //获取每个img标签中的src   
  11.     }                                                         
  12.     // Find all links                                                 
  13.     foreach($dom->find('a') as $element){ //获取a标签的数组                                           
  14.     echo $element->href . '<br>';//获取每个a标签中的href                                 
  15.     }  
  16.     $html = file_get_html('http://slashdot.org/'); //获取html                                  
  17.     $dom = new simple_html_dom(); //new simple_html_dom对象                                  
  18.     $dom->load($html); //加载html                                           
  19.     // Find all article blocks                                            
  20.     foreach($dom->find('div.article') as $article) {                                             
  21.     $item['title'] = $article->find('div.title', 0)->plaintext; //plaintext 获取纯文本  
  22.     $item['intro'] = $article->find('div.intro', 0)->plaintext;                                
  23.     $item['details'] = $article->find('div.details', 0)->plaintext;                                  
  24.     $articles[] = $item;  
  25.     }  
  26. print_r($articles);   
  27.   
  28.     // Create DOM from string      
  29. $html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');    
  30.     $dom = new simple_html_dom();     //new simple_html_dom对象</p><p>      
  31.     $dom->load($html);      //加载html    
  32.     $dom->find('div', 1)->class = 'bar';    //class = 赋值 给第二个div的class赋值</p><p>     
  33.     $dom->find('div[id=hello]', 0)->innertext = 'foo';   //innertext内部文本</p><p>      
  34.     echo $dom;   
  35.       
[html] view plain copy
  1. //Output:   
  2.    <div id="hello">foo</div><div id="world" class="bar">World</div>  
  3.    <p> DOM methods & properties     
  4.     Name Description     
  5.     void __construct ( [string $filename] ) 构造函数,将文件名参数将自动加载内容,无论是文本或文件/ url。     
  6.     string plaintext 纯文本     
  7.     void clear () 清理内存     
  8.     void load ( string $content ) 加载内容     
  9.     string save ( [string $filename] ) Dumps the internal DOM tree back into a string. If the $filename is set, result string   will save to file.     
  10.     void load_file ( string $filename ) Load contents from a from a file or a URL.     
  11.     void set_callback ( string $function_name ) 设置一个回调函数。     
  12.     mixed find ( string $selector [, int $index] ) 找到元素的CSS选择器。返回第n个元素对象如果索引设置,否则返回一个数组对象。 </p>   


  1.     4.find 方法详细介绍</p><p>  
  2.     find ( string $selector [, int $index] )   
  3.     // Find all anchors, returns a array of element objects a标签数组  
  4.     $ret = $html->find('a');</p><p>  // Find (N)th anchor, returns element object or null if not found (zero based)第一个a标签  
  5.     $ret = $html->find('a', 0);</p><p>   // Find lastest anchor, returns element object or null if not found (zero based)最后一个a标签  
  6.     $ret = $html->find('a', -1); </p><p> // Find all <div> with the id attribute   
  7.     $ret = $html->find('div[id]');</p><p>    // Find all <div> which attribute id=foo  
  8.     $ret = $html->find('div[id=foo]'); </p><p>  
  9.     // Find all element which id=foo  
  10.     $ret = $html->find('#foo');</p><p>   // Find all element which class=foo  
  11.     $ret = $html->find('.foo');</p><p>   // Find all element has attribute id  
  12.     $ret = $html->find('*[id]'); </p><p> // Find all anchors and images a标签与img标签数组   
  13.     $ret = $html->find('a, img');  </p><p>  // Find all anchors and images with the "title" attribute  
  14.     $ret = $html->find('a[title], img[title]');</p><p>  
  15.     // Find all <li> in <ul>   
  16.     $es = $html->find('ul li'); ul标签下的li标签数组</p><p>  // Find Nested <div> tags  
  17.     $es = $html->find('div div div');  div标签下div标签下div标签数组</p><p>   // Find all <td> in <table> which class=hello   
  18.     $es = $html->find('table.hello td'); table标签下td标签数组</p><p>   // Find all td tags with attribite align=center in table tags   
  19.     $es = $html->find(''table td[align=center]'); </p><p>   
  20.     5.Element  的方法  
  21.     $e = $html->find("div", 0);                              //$e 所拥有的方法如下表所示  
  22.     Attribute Name Usage   
  23.     $e->tag 标签   
  24.     $e->outertext 外文本   
  25.     $e->innertext 内文本   
  26.     $e->plaintext 纯文本 </p><p> </p><p>   // Example  
  27.     $html = str_get_html("<div>foo <b>bar</b></div>");   
  28.     echo $e->tag; // Returns: " div"  
  29.     echo $e->outertext; // Returns: " <div>foo <b>bar</b></div>"  
  30.     echo $e->innertext; // Returns: " foo <b>bar</b>"  
  31.     echo $e->plaintext; // Returns: " foo bar"</p><p>  
  32.     6.DOM traversing 方法  
  33.     Method Description   
  34.     mixed$e->children ( [int $index] ) 子元素   
  35.     element$e->parent () 父元素   
  36.     element$e->first_child () 第一个子元素   
  37.     element$e->last_child () 最后一个子元素   
  38.     element$e->next_sibling () 后一个兄弟元素   
  39.     element$e->prev_sibling () 前一个兄弟元素 </p><p>  
  40.     // Example  
  41.     echo $html->find("#div1", 0)->children(1)->children(1)->children(2)->id;  
  42.     // or   
  43.     echo $html->getElementById("div1")->childNodes(1)->childNodes(1)->childNodes(2)->getAttribute('id');  
  44. </p>  

原创粉丝点击