讲解thinkphp5.1如何实现多线程爬虫
时间:2021-11-15
来源:互联网
标签:
今天PHP爱好者给大家带来下面thinkphp框架教程栏目将给大家讲解thinkphp5.1 利用cli命令行+Guzzle类库实现多线程爬虫,希望对需要的朋友有所帮助!
创建一个cli命令
php think make:command Thread thread
测试能否成功执行
php think thread
安装Guzzle类库
文档地址:guzzle文档地址(https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html)
实现代码
<?php
/**
* Created by.
* User: Jim
* Date: 2020/9/29
* Time: 14:31
*/
namespace app\command;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use think\console\Command;
use think\console\Input;
use think\console\Output;
/**
* Guzzle
* Class Thread
* @package app\command
* 文档地址 https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html
*/
class Thread extends Command
{
/**
* 请求的总次数
* @var int
*/
protected $totalPageCount = 50;
/**
* 当前请求的次数
* @var int
*/
protected static $counter = 1;
/**
* 线程的数量
* @var int
*/
protected $threads = 20;
protected function configure()
{
// 指令配置
$this->setName('thread');
// 设置参数
}
protected function execute(Input $input, Output $output)
{
$client = new Client();
$requests = function ($total) use ($client) {
foreach (range(1, $total) as $r) {
$uri = 'https://apinew.juejin.im/content_api/v1/short_msg/detail';
yield function () use ($client, $uri) {
return $client->postAsync($uri, [
'verify' => false,
'json' => [
'msg_id' => '6845185452727599118'
]
]);
};
}
};
$pool = new Pool($client, $requests($this->totalPageCount), [
'concurrency' => $this->threads,
// 请求成功
'fulfilled' => function ($response, $index) use ($output) {
$res = $response->getBody()->getContents();
$output->writeln($res);
$output->writeln("正在执行第{$index}个·····");
if ($this->checkThreadIsEnd() == true) {
$output->writeln("------------请求结束---------");
return false;
}
},
// 请求失败
'rejected' => function ($reason, $index) use ($output) {
$output->writeln("执行失败,{$reason}");
},
]);
$promise = $pool->promise();
$promise->wait();
}
/**
* 检测任务是否结束
* @return bool
*/
private function checkThreadIsEnd()
{
if (self::$counter < $this->totalPageCount) {
self::$counter++;
return false;
} else {
return true;
}
}
}
执行命令
php think thread
效果

以上就是讲解thinkphp5.1如何实现多线程爬虫的详细内容,更多请关注php爱好者其它相关文章!
-
USB Host接口有什么用?USB Host和USB Device接口的区别 时间:2025-12-16 -
HDMI怎么区分1.4和2.0?HDMI1.4和2.0的区别 时间:2025-12-16 -
com.android.phone已停止运行是什么意思?怎么解决? 时间:2025-12-16 -
4mp摄像头是多少像素?4mp和1080p有什么区别? 时间:2025-12-16 -
电脑出现normal.dotm错误怎么办?解决方法是什么? 时间:2025-12-15 -
normal.dotm在哪个文件夹里 如何删除normal模板 时间:2025-12-15
今日更新
-
chess online官网登录入口-chess online网站快捷登录入口
阅读:18
-
欧易邀请好友奖励机制详解 如何获得高额返利
阅读:18
-
哔哩哔哩官网网页直播回放观看入口-哔哩哔哩官网网页快捷入口
阅读:18
-
云原神网页版登录入口位置详解
阅读:18
-
ps5港服官网入口地址-ps5港版注册登录通道
阅读:18
-
批作业是什么梗?揭秘学生党崩溃瞬间,看完笑出眼泪!
阅读:18
-
原神在线畅玩云游戏官网-原神网页版一键登录秒玩
阅读:18
-
邀请好友赢取丰厚奖励,最高可得XX元!
阅读:18
-
搜红包最新活动入口2026
阅读:18
-
126邮箱登录入口一键直达-126网易免费邮箱官网镜像极速稳定登录
阅读:18










