1. 程式人生 > >php抓取網頁內容,獲取網頁資料

php抓取網頁內容,獲取網頁資料

php通過simple_html_dom實現抓取網頁內容,獲取核心網頁資料,將網頁資料寫入本地 xxx.json 檔案

其程式碼實現邏輯:

1. 引入simple_html_dom.php檔案

     

 require_once 'simple_html_dom-master/simple_html_dom.php';

2. 獲取遠端或者本地html檔案

   

$html = file_get_html('./imooc.html');

3. 建立要獲取資料的陣列

    $cases =  Array();
    $arrImg = Array();

4. 獲取當前網頁所有案例圖片、標題、觀看人數、等級、價格

      foreach($html->find('.shizhan-course-wrap') as $element) 
       {
        $arrImg['img']  =  "http:".$element->find('.shizhan-course-img',0)->src;
        $arrImg['intro']  =  $element->find('.shizan-name',0)->plaintext;
        $arrImg['degree']  =  $element->find('.grade',0)->plaintext;
        $arrImg['views']  =  $element->find('.shizhan-info>span',1)->plaintext;
        $arrImg['desc']  =  $element->find('p.shizan-desc',0)->plaintext;
        $arrImg['price']  =  $element->find('div.course-card-price',0)->plaintext;
        $arrImg['link']  =  "http://coding.imooc.com".$element->find('a',0)->href;

        $cases[] = $arrImg;
       }

5. 生成json格式,寫入本地檔案imooc.json

    $json = json_encode($cases);
    file_put_contents('imooc.json', $json);

6. 通過其他html頁面ajax呼叫本地json檔案

~function(){
    function ajax(url,fn){
       var xhr = new XMLHttpRequest();
       xhr.open('get',url,true);
       xhr.send();
       xhr.onload = function(ev){
          fn(ev);
       }
    }

    ajax('./imooc.json',function(ev){
       var data = JSON.parse(ev.currentTarget.response);
       console.log(data);
     })
}();

7. 列印臺輸出內容:

8. 至於其獲取元素相關的語法操作類似於jquery獲取元素操作,請閱讀線上網頁文件:

    http://simplehtmldom.sourceforge.net/manual.htm

9. 其simple_dom_html類庫下載地址:

    連結:https://pan.baidu.com/s/1o8mlw98 密碼:im5q