標籤:c style class blog code java
今天來做一個PHP電影小爬蟲。
我們來利用simple_html_dom的採集資料執行個體,這是一個PHP的庫,上手很容易。
simple_html_dom 可以很好的協助我們利用php解析html文檔。通過這個php封裝類可以很方便的解析html文檔,對其中的html元素進行操作 (PHP5+以上版本)
:https://github.com/samacs/simple_html_dom
下面我們以 http://www.paopaotv.com 上的列表頁 http://paopaotv.com/tv-type-id-5-pg-1.html 字母模式展現的列表為例,抓取頁面上的列表資料,以及內容裡面資訊
1 <?php 2 include_once ‘simple_html_dom.php‘; 3 //擷取html資料轉化為對象 4 $html = file_get_html(‘http://paopaotv.com/tv-type-id-5-pg-1.html‘); 5 //A-Z的字母列表每條資料是在id=letter-focus 的div內class= letter-focus-item的dl標籤內,用find方法尋找即為 6 $listData=$html->find("#letter-focus .letter-focus-item");//$listData為數組對象 7 foreach($listData as$key=>$eachRowData){ 8 $filmName=$eachRowData->find("dd span",0)->plaintext;//擷取影視名稱 9 $filmUrl=$eachRowData->find("dd a",0)->href;//擷取dd標籤下影視對應的地址10 //擷取影視的詳細資料11 $filmInfo=file_get_html("http://paopaotv.com".$filmUrl);12 $filmDetail=$filmInfo->find(".info dl");13 foreach($filmDetail as $film){14 $info=$film->find("dd");15 $row=null;16 foreach($info as $childInfo){17 $row[]=$childInfo->plaintext;18 }19 $cate[$key][]=join(",",$row);//將影視的資訊存放到數組中20 }21 }
這樣通過simple_html_dom,就可以將paopaotv.com影視列表中資訊,以及影視的具體資訊就抓取到了,之後你可以繼續抓取影視詳細頁面上的視頻地址資訊,然後將該影視的所有資訊都存放到資料庫中。
下面是simple_html_dom常用的屬性以及方法:
1 $html = file_get_html(‘http://paopaotv.com/tv-type-id-5-pg-1.html‘); 2 $e = $html->find("div", 0); 3 //標籤 4 $e->tag; 5 //外文本 6 $e->outertext; 7 //內文本 8 $e->innertext; 9 //純文字10 $e->plaintext;11 //子項目12 $e->children ( [int $index] );13 //父元素14 $e->parent ();15 //第一個子項目16 $e->first_child ();17 //最後一個子項目18 $e->last_child ();19 //後一個兄弟元素20 $e->next_sibling ();21 //前一個兄弟元素22 $e->prev_sibling ();23 //標籤數組24 $ret = $html->find(‘a‘);25 //第一個a標籤26 $ret = $html->find(‘a‘, 0);
更多用法可以參考官方手冊。
是不是很簡單呢?有問題歡迎提出來交流