PHP采集任意网址自动识别并提取页面主体内容

admin2024-04-03  0

对于PHP采集很多种方式,但是都是指定dom哪个节点来采集内容,这样太麻烦了,有没有一方式可以任意网址可以自动识别主本内容呢。答案是有。
用到的组件:

  • QueryList:先用Queyrylist采集页面内容html
  • readability:把采集到的HTML原始内容给readability分析树结构,提取页面内容。

组件仓库地址:
https://querylist.cc/
https://github.com/andreskrey/readability.php
看效果:
PHP采集任意网址自动识别并提取页面主体内容,在这里插入图片描述,第1张
PHP采集任意网址自动识别并提取页面主体内容,在这里插入图片描述,第2张
代码:

public function readability()
    {
        $param = $this->request->param();
        if($this->request->isPost())
        {
            $url = trim($param['url']);

            $ql = QueryList::get($url);
            $html = $ql->getHtml();
            //$html = file_get_contents($url);
            //$html = HttpService::request($url);

            $rules = [
                'keywords' => ['meta[name=keywords]','content'],
                'description' => ['meta[name=description]','content']
            ];
            $query =  $ql->rules($rules)->queryData();

            $readability = new Readability(new Configuration());
            $readability->parse($html);


            $data['title'] = $readability->getTitle();
            $data['seo_title'] = $readability->getTitle();
            $data['keywords'] = $query['keywords'];
            $data['description'] = '';
            $data['source'] = $url;
            $data['status'] = true;

            $content = $readability->getContent();
            $content = preg_replace("/<!--[^\!\[]*?(?<!\/\/)-->/","",$content);//删除注释
            $content = preg_replace("/<div (id|class)=('|\")(.*?)(\'|\")>/","",$content);//删除最外层idv
            $content = preg_replace("/(↵|\r\n|\n|\r)<\/div>$/","",$content);//删除最外层idv

            $data['content'] = $content;
            $data['thumb'] = $readability->getImage();
            $images = $readability->getImages();
            $photos = [];
            if(!empty($images))
            {
                foreach($photos as $v)
                {
                    $photo = [
                        'src'   => $v,
                        'alt'   => '',
                    ];
                    array_push($photos,$photo);
                }
                $data['photos'] = $photos;
            }


            return $data;
        }
        else
        {
            return $this->fetch();
        }

    }
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!