[精选] PHP也是可以用来做异步爬取数据的
优采云 发布时间: 2022-07-04 21:21[精选] PHP也是可以用来做异步爬取数据的
$ql = QueryList::getInstance();<br style="outline: 0px;" /><br style="outline: 0px;" />//绑定一个myHttp方法到QueryList对象<br style="outline: 0px;" />$ql->bind('myHttp',function ($url){<br style="outline: 0px;" /> $html = file_get_contents($url);<br style="outline: 0px;" /> $this->setHtml($html);<br style="outline: 0px;" /> return $this;<br style="outline: 0px;" />});<br style="outline: 0px;" /><br style="outline: 0px;" />//然后就可以通过注册的名字来调用<br style="outline: 0px;" />$data = $ql->myHttp('https://toutiao.io')->find('h3 a')->texts();<br style="outline: 0px;" />print_r($data->all());<br style="outline: 0px;" />
或者把实现体封装到class,然后这样绑定:
$ql->bind('myHttp',function ($url){<br style="outline: 0px;" /> return new MyHttp($this,$url);<br style="outline: 0px;" />});<br style="outline: 0px;" />
插件使用
使用CURL多线程插件,多线程采集GitHub排行榜:
$ql = QueryList::use(CurlMulti::class);<br style="outline: 0px;" />$ql->curlMulti([<br style="outline: 0px;" /> 'https://github.com/trending/php',<br style="outline: 0px;" /> 'https://github.com/trending/go',<br style="outline: 0px;" /> //.....more urls<br style="outline: 0px;" />])<br style="outline: 0px;" /> // 每个任务成功完成调用此回调<br style="outline: 0px;" /> ->success(function (QueryList $ql,CurlMulti $curl,$r){<br style="outline: 0px;" /> echo "Current url:{$r['info']['url']} \r\n";<br style="outline: 0px;" /> $data = $ql->find('h3 a')->texts();<br style="outline: 0px;" /> print_r($data->all());<br style="outline: 0px;" />})<br style="outline: 0px;" /> // 每个任务失败回调<br style="outline: 0px;" />->error(function ($errorInfo,CurlMulti $curl){<br style="outline: 0px;" /> echo "Current url:{$errorInfo['info']['url']} \r\n";<br style="outline: 0px;" /> print_r($errorInfo['error']);<br style="outline: 0px;" />})<br style="outline: 0px;" />->start([<br style="outline: 0px;" /> // 最大并发数<br style="outline: 0px;" /> 'maxThread' => 10,<br style="outline: 0px;" /> // 错误重试次数<br style="outline: 0px;" /> 'maxTry' => 3,<br style="outline: 0px;" />]);<br style="outline: 0px;" />
更多详细请查看GitHub:
让你更好的学习php爬虫,小编推荐一套视频教程【ThinkPHP6+Querylist实战开发】希望以后你们能用得着。
获取地址:
课程目录
课时1 实战实录 tp6开发PHP手册统计项目 - 介绍09:29
课时2【实战实录】PHP手册统计-项目分析09:45
课时3【实战实录】PHP手册统计用querylist采集08:56
课时4 PHP手册统计获取到了一个文件的所属上级04:22
课时5 PHP手册统计建立表对接15040个页面10:01
课时6 PHP手册统计完成15037个页面名称存入数据库05:58
课时7 完成了除包含php字符的对应目录的入库12:03
课时8 初步实现和了解了php手册各栏目的页面数量12:20
课时9 v1.0版上线源码可以通过github查看通过composer安装06:25
课时10 入门php的cli命令行模式 即使获得进度13:14
课时11 正式进入v2.0版本 cli模式作为主要运行对象09:30
课时12 实现了一级目录的数据量统计11:26
课时13 重写了一个激动人心的采集规则22:26
课时14 针对目录不一致问题 增加字段统计比对05:16
课时15 应用递归实现从文件获取其完整目录12:27
课时16 通过递归补齐没有path的文件17:01
课时17 用递归排查完成总数不一致问题08:10
课时18 用递归完成了基本tree树形分类14:49
课时19 完成前端tree树形分类用zTree实现08:10
课时20 完成前端11个栏目的树形分类11:41
课时21 第一版完可以预览子目录数量的目录完成07:16
课时22 第一版完可以预览子目录数量的目录完成07:16
课时23 完成第一套完整的统计带统计分析的php手册12:50
课时24 统计结果html上线gitee直接浏览07:26
课时25 PHP手册统计项目 - 总结
文章来自:
END