文章出處
文章列表
使用simple_html_dom.php,下載|文檔
因為抓取的只是一個網頁,所以比較簡單,整個網站的下次再研究,可能用Python來做爬蟲會好些。
1 <meta http-equiv="content-type" content="text/html;charset=utf-8"/> 2 <?php 3 include_once 'simplehtmldom/simple_html_dom.php'; 4 //獲取html數據轉化為對象 5 $html = file_get_html('http://paopaotv.com/tv-type-id-5-pg-1.html'); 6 //A-Z的字母列表每條數據是在id=letter-focus 的div內class= letter-focus-item的dl標簽內,用find方法查找即為 7 8 foreach($html->find('.txt-list li a') as $element) 9 $arr[]= $element->innertext . '<br>'; 10 11 $fileName='data.txt';//不用事先建好 12 $arrLen=count($arr); 13 for($i=0;$i<$arrLen;$i++){ 14 file_put_contents($fileName,$arr[$i],FILE_APPEND|LOCK_EX); 15 /*FILE_APPEND|LOCK_EX是往后追加數據,如果沒有該參數,則只能插入一條數據 16 但是如果重新啟動抓取時,則會將以往抓取過的數據繼續存入*/ 17 } 18 //以上是抓取的數據然后存到data.text里 19 $content=file_get_contents($fileName); 20 $cont=explode("<br>",$content); 21 $contLen=count($cont); 22 for($i=0;$i<$contLen;$i++) { 23 unset($cont[2*$i+1]); 24 }
先在 http://www.paopaotv.com/tv-type-id-5-pg-1.html 中找到節點,
1 foreach($html->find('.txt-list li a') as $element) 2 $arr[]= $element->innertext . '<br>';
獲得節點內的數據
獲得的數據:
可以看到,每個獲取的數據后面都有個<br>***<br>,這時因為 .txt-list li 下面有兩個a,所以會得到兩個數據
1 $content=file_get_contents($fileName); 2 $cont=explode("<br>",$content); 3 $contLen=count($cont); 4 for($i=0;$i<$contLen;$i++) { 5 unset($cont[2*$i+1]); 6 }
獲取data.text中的數據,通過 explode("<br>",$content) 將<br>前后的數據分成兩部分,將$cont用print_r()函數打印出來后,得到
可以看出,所有不需要的數據都是奇數項,所以用 unset($cont[2*$i+1]); 函數刪掉,顯示的時候是:
但是如何將現在的數組的key重新排序,這個我還沒不知道怎么弄,試過array_splice,該函數也不能設定只支持刪除奇數的內容。
文章列表
全站熱搜