讲解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爱好者其它相关文章!
-
WebStorm干嘛用的 WebStorm和VSCode哪个好用 时间:2025-09-13
-
PyCharm详细的安装及使用教程 时间:2025-09-13
-
PyCharm是干什么用的 PyCharm和Python的区别 时间:2025-09-13
-
PHP运行环境的搭建方法及流程详解 时间:2025-09-13
-
PHPstorm环境配置与应用 PHPstorm怎么配置PHP环境 时间:2025-09-13
-
PHP date()函数详解(定义、语法、用法) 时间:2025-09-13
今日更新
-
天空梗是什么梗?揭秘网络爆火天空表情包的搞笑起源与玩法
阅读:18
-
想知道天籁是什么梗?揭秘网络热词天籁的爆笑来源和流行用法!
阅读:18
-
想知道天蓝怪是什么梗吗?揭秘这个火爆网络的神秘热词,让你秒懂潮流!
阅读:18
-
天蓝怪行为是什么梗?揭秘网络爆火神秘现象背后的搞笑真相!
阅读:18
-
重返未来:1999新角色野树莓-野树莓抽取建议
阅读:18
-
以闪亮之名全新主线之旅-章节第36章即将开启
阅读:18
-
梦幻西游恶魔泡泡怎么获得-恶魔泡泡获取方法
阅读:18
-
崩坏星穹铁道3.6版本新内容公布-可免费获五星角色
阅读:18
-
天雷滚滚是什么梗?揭秘网络热词背后的爆笑名场面
阅读:18
-
如鸢袁基大活月海夜航船活动-1-16关入夜详细
阅读:18