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

猜你喜欢

转载自blog.csdn.net/WU5229485/article/details/82952457