1. 程式人生 > >php解析html類庫simple_html_dom(爬蟲相關)

php解析html類庫simple_html_dom(爬蟲相關)

下載地址:https://github.com/samacs/simple_html_dom

解析器不僅僅只是幫助我們驗證html文件;更能解析不符合W3C標準的html文件。它使用了類似jQuery的元素選擇器,通過元素的id,class,tag等等來查詢定位;同時還提供新增、刪除、修改文件樹的功能。當然,這樣一款強大的html Dom解析器也不是盡善盡美;在使用的過程中需要十分小心記憶體消耗的情況。不過,不要擔心;本文中,筆者在最後會為各位介紹如何避免消耗過多的記憶體。
開始使用
上傳類檔案以後,有三種方式呼叫這個類:
從url中載入html文件
從字串中載入html文件
從檔案中載入html文件
<?php
// 新建一個Dom例項
$html = new simple_html_dom();

// 從url中載入
$html->load_file('http://www.jb51.net');

// 從字串中載入
$html->load('<html><body>從字串中載入html文件演示</body></html>');

//從檔案中載入
$html->load_file('path/file/test.html');
?>


如果從字串載入html文件,需要先從網路上下載。建議使用CURL來抓取html文件並載入DOM中。

PHP Simple HTML DOM Parser提供了3種方式來建立DOM物件 :

// Create a DOM object from a string 
$html = str_get_html('<html><body>Hello!</body></html>'); 
// Create a DOM object from a URL 
$html = file_get_html('http://www.google.com/'); 
// Create a DOM object from a HTML file 
$html = file_get_html('test.htm'); 


查詢html元素
可以使用find函式來查詢html文件中的元素。返回的結果是一個包含了物件的陣列。我們使用HTML DOM解析類中的函式來訪問這些物件,下面給出幾個示例:
<?php

//查詢html文件中的超連結元素
$a = $html->find('a');

//查詢文件中第(N)個超連結,如果沒有找到則返回空陣列.
$a = $html->find('a', 0);

// 查詢id為main的div元素
$main = $html->find('div[id=main]',0);

// 查詢所有包含有id屬性的div元素
$divs = $html->find('div[id]');

// 查詢所有包含有id屬性的元素
$divs = $html->find('[id]');
?>



還可以使用類似jQuery的選擇器來查詢定位元素:
<?php
// 查詢id='#container'的元素
$ret = $html->find('#container');

// 找到所有class=foo的元素
$ret = $html->find('.foo');

// 查詢多個html標籤
$ret = $html->find('a, img');

// 還可以這樣用
$ret = $html->find('a[title], img[title]');
?>


解析器支援對子元素的查詢
<?php

// 查詢 ul列表中所有的li項
$ret = $html->find('ul li');

//查詢 ul 列表指定class=selected的li項
$ret = $html->find('ul li.selected');

?>


如果你覺得這樣用起來麻煩,使用內建函式可以輕鬆定位元素的父元素、子元素與相鄰元素
<?php
// 返回父元素
$e->parent;

// 返回子元素陣列
$e->children;

// 通過索引號返回指定子元素
$e->children(0);

// 返回第一個資源速
$e->first_child ();

// 返回最後一個子元素
$e->last _child ();

// 返回上一個相鄰元素
$e->prev_sibling ();

//返回下一個相鄰元素
$e->next_sibling ();
?>



元素屬性操作
使用簡單的正則表示式來操作屬性選擇器。
[attribute] – 選擇包含某屬性的html元素
[attribute=value] – 選擇所有指定值屬性的html元素
[attribute!=value]- 選擇所有非指定值屬性的html元素
[attribute^=value] -選擇所有指定值開頭屬性的html元素
[attribute$=value] 選擇所有指定值結尾屬性的html元素
[attribute*=value] -選擇所有包含指定值屬性的html元素
在解析器中呼叫元素屬性
在DOM中元素屬性也是物件:
<?php
// 本例中將$a的錨鏈接值賦給$link變數
$link = $a->href;
?>

或者:
<?php
$link = $html->find('a',0)->href;
?


每個物件都有4個基本物件屬性:
tag – 返回html標籤名
innertext – 返回innerHTML
outertext – 返回outerHTML
plaintext – 返回html標籤中的文字
在解析器中編輯元素
編輯元素屬性的用法和呼叫它們是類似的:
<?php
//給$a的錨鏈接賦新值
$a->href = 'http://www.jb51.net';

// 刪除錨鏈接
$a->href = null;

// 檢測是否存在錨鏈接
if(isset($a->href)) {
//程式碼
}
?>


解析器中沒有專門的方法來新增、刪除元素,不過可以變通一下使用:
<?php
// 封裝元素
$e->outertext = '<div class="wrap">' . $e->outertext . '<div>';

// 刪除元素
$e->outertext = '';

// 新增元素
$e->outertext = $e->outertext . '<div>foo<div>';

// 插入元素
$e->outertext = '<div>foo<div>' . $e->outertext;
?>



儲存修改後的html DOM文件也非常簡單:
<?php
$doc = $html;
// 輸出
echo $doc;
?>



如何避免解析器消耗過多記憶體
在本文的開篇中,筆者就提到了Simple HTML DOM解析器消耗記憶體過多的問題。如果php指令碼佔用記憶體太多,會導致網站停止響應等一系列嚴重的問題。解決的方法也很簡單,在解析器載入html文件並使用完成後,記得清理掉這個物件就可以了。當然,也不要把問題看得太嚴重了。如果只是載入了2、3個文件,清理或不清理是沒有多大區別的。當你載入了5個10個甚至更多的文件的時候,用完一個就清理一下記憶體
<?php
$html->clear();
?>


一個例項:

<p>簡單範例  
<?PHP
    include "simple_html_dom.php" ;//載入simple_html_dom.php檔案  
    $html = file_get_html('http://www.google.com/');//獲取html                            
    $dom = new simple_html_dom(); //new simple_html_dom物件                            
    $dom->load($html)  //載入html                                            
    // Find all images                                          
    foreach($dom->find('img') as $element) {   
    //獲取img標籤陣列                                      
	    echo $element->src . '<br>'; //獲取每個img標籤中的src 
	}                                                       
    // Find all links                                               
    foreach($dom->find('a') as $element){ //獲取a標籤的陣列                                         
    echo $element->href . '<br>';//獲取每個a標籤中的href                               
	}
    $html = file_get_html('http://slashdot.org/'); //獲取html                                
    $dom = new simple_html_dom(); //new simple_html_dom物件                                
    $dom->load($html); //載入html                                         
    // Find all article blocks                                          
    foreach($dom->find('div.article') as $article) {                                           
    $item['title'] = $article->find('div.title', 0)->plaintext; //plaintext 獲取純文字
    $item['intro'] = $article->find('div.intro', 0)->plaintext;                              
    $item['details'] = $article->find('div.details', 0)->plaintext;                                
    $articles[] = $item;
	}
print_r($articles); 

    // Create DOM from string    
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');  
    $dom = new simple_html_dom();     //new simple_html_dom物件</p><p>    
    $dom->load($html);      //載入html  
    $dom->find('div', 1)->class = 'bar';    //class = 賦值 給第二個div的class賦值</p><p>   
    $dom->find('div[id=hello]', 0)->innertext = 'foo';   //innertext內部文字</p><p>    
    echo $dom; 
    
 //Output: 
    <div id="hello">foo</div><div id="world" class="bar">World</div>
    <p> DOM methods & properties   
    	Name Description   
    	void __construct ( [string $filename] ) 建構函式,將檔名引數將自動載入內容,無論是文字或檔案/ url。   
    	string plaintext 純文字   
    	void clear () 清理記憶體   
    	void load ( string $content ) 載入內容   
    	string save ( [string $filename] ) Dumps the internal DOM tree back into a string. If the $filename is set, result string   will save to file.   
    	void load_file ( string $filename ) Load contents from a from a file or a URL.   
    	void set_callback ( string $function_name ) 設定一個回撥函式。   
    	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>