http://www.google.com.hk/ 用php解析html的實作程式碼

WBOY
發布: 2016-07-29 08:46:30
原創
1492 人瀏覽過

最近想用php寫一個爬蟲,就需要解析html,在sourceforge上找到一個專案叫做PHP Simple HTML DOM Parser,它可以以類似jQuery的方式透過css選擇器來傳回指定的DOM元素,功能十分強大。
首先要在程式的開始引入simple_html_dom.php這個檔案

複製程式碼 程式碼如下:


include_once('siplemple_html_dom.php');建立DOM物件



複製程式碼

程式碼如下:// Create a DOM object from a string

$html = str_get_html('bodyHello!Hello );

// 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');


得到DOM物件後就可以進行各種操作了



複製程式碼

程式碼如下:// Find all anchors, returnsement arra即使$html->find('a');

// Find (N)th anchor, returns element object or null if not found (zero based)

$ret = $html->find('a', 0);
// Find lastest anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', -1);
// Find all

with the id attriute
$ret = $html->find('div[id]');
// Find all
which attribute id=foo
$ret = $html->find('div[id=foo]');


這裡可以使用各種css選擇器,就像在jQuery中進行DOM操作一樣,非常方便。此外,還有兩個特殊的屬性可以得到文字和註解的內容


複製程式碼

程式碼如下:// Find all text blocks $es = $html->find('text') ;

// Find all comment () blocks

$es = $html->find('comment');


當然,還是類似jQuery,PHP Simple HTML DOM Parser也支援鍊式操作,以及各種存取DOM元素的簡單方法


複製程式碼

程式碼如下:// Example echo $html->find("#div1", 0)->ren (1)->children(1)->children(2)->id;

// or

echo $html->getElementById("div1")->childNodes(1)->childNodes(1)->childNodes (2)->getAttribute('id');


以上就介紹了http://www.google.com.hk/ 用php解析html的實作程式碼,包括了http://www.google.com.hk/方面的內容,希望對PHP教學有興趣的朋友有所幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!