thinkphp5 用QueryList3抓取网页内容

作者: siediyer 分类: PHP 发布时间: 2024-06-06 15:30

Thinkphp5 官网下载地址:http://www.thinkphp.cn/

Thinkphp5 百度网盘下载地址:链接:https://pan.baidu.com/s/1GtmdNk8Xrz6YogZs10ExkA 提取码:mzdw

QueryList Github下载地址:https://github.com/jae-jae/QueryList/tree/V3.2.1

phpQuery Github下载地址:https://github.com/jae-jae/phpQuery-single

百度网盘下载地址:链接:https://pan.baidu.com/s/1OKRYlLG8mvLjrRRLd-x8zg 提取码:kyym

下载`QueryList.php`和`phpQuery.php`这两个文件

修改QueryList源码,加上下面这句话:

require 'phpQuery.php';

在` extend`下新建`QL`目录,将下载好的`QueryList.php`和`phpQuery.php`这两个文件复制到该目录。

PHP代码

<?php
namespace app\index\controller;
use think\Controller;
use think\Loader;
use QL\QueryList;

class Index extends Controller
{
    public function index()
    {
        //采集某页面所有的超链接
        $d = QueryList::Query('http://cms.querylist.cc/bizhi/453.html',['link' => ['a','href']])->data;
        //打印结果
        print_r($d);
    }
}

 

use QL\QueryList;

//需要采集的目标页面
       $page = 'http://cms.querylist.cc/news/566.html';
//采集规则
       $reg = array(
           //采集文章标题
           'title' => array('h1','text'),
           //采集文章发布日期,这里用到了QueryList的过滤功能,过滤掉span标签和a标签
           'date' => array('.pt_info','text','-span -a',function($content){
               //用回调函数进一步过滤出日期
               $arr = explode(' ',$content);
               return $arr[0];
           }),
           //采集文章正文内容,利用过滤功能去掉文章中的超链接,但保留超链接的文字,并去掉版权、JS代码等无用信息
           'content' => array('.post_content','html','a -.content_copyright -script',function($content){
               //利用回调函数下载文章中的图片并替换图片路径为本地路径
               //使用本例请确保当前目录下有image文件夹,并有写入权限
               //由于QueryList是基于phpQuery的,所以可以随时随地使用phpQuery,当然在这里也可以使用正则或者其它方式达到同样的目的

               $doc=\phpQuery::newDocumentHTML($content);
               $imgs = pq($doc)->find('img');
               foreach ($imgs as $img) {
                   $src = 'http://cms.querylist.cc'.pq($img)->attr('src');
                   $localSrc = md5($src).'.jpg';
                   $stream = file_get_contents($src);
                   file_put_contents($localSrc,$stream);
                   pq($img)->attr('src',$localSrc);
               }
               return $doc->htmlOuter();
           })
       );
       $rang = '.content';
       $ql = QueryList::Query($page,$reg,$rang);
       $data = $ql->getData();
//打印结果
       print_r($data);

注意:在使用phpQuery类时需要在前面加上\,因为phpQuery.php中没有使用命名空间,因为使用命名空间后,QueryList.php无法使用phpQuery类
QueryList参考文档:https://doc.querylist.cc/

phpQuery-single-master
QueryList-3.2.1

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

Title - Artist
0:00