本文实例讲述了php使用pthreads v3多线程实现抓取新浪新闻信息。分享给大家供大家参考,具体如下:
我们使用pthreads,来写一个多线程的抓取页面小程序,把结果存到数据库里。
数据表结构如下:
create table `tb_sina` ( `id` int(11) unsigned not null auto_increment comment 'id', `url` varchar(256) default '' comment 'url地址', `title` varchar(128) default '' comment '标题', `time` datetime default null on update current_timestamp comment '时间', primary key (`id`) ) engine=innodb default charset=utf-8 comment='sina新闻';
代码如下:
<?php
class db extends worker
{
private static $db;
private $dsn;
private $root;
private $pwd;
public function __construct($dsn, $root, $pwd)
{
$this->dsn = $dsn;
$this->root = $root;
$this->pwd = $pwd;
}
public function run()
{
//创建连接对象
self::$db = new pdo($this->dsn, $this->root, $this->pwd);
//把require放到worker线程中,不要放到主线程中,不然会报错找不到类
require './vendor/autoload.php';
}
//返回一个连接资源
public function getconn()
{
return self::$db;
}
}
class sina extends thread
{
private $name;
private $url;
public function __construct($name, $url)
{
$this->name = $name;
$this->url = $url;
}
public function run()
{
$db = $this->worker->getconn();
if (empty($db) || empty($this->url)) {
return false;
}
$content = file_get_contents($this->url);
if (!empty($content)) {
//获取标题,地址,时间
$data = ql\querylist::query($content, [
'tit' => ['.c_tit > a', 'text'],
'url' => ['.c_tit > a', 'href'],
'time' => ['.c_time', 'text'],
], '', 'utf-8', 'gb2312')->getdata();
//把获取的数据插入数据库
if (!empty($data)) {
$sql = 'insert into tb_sina(`url`, `title`, `time`) values';
foreach ($data as $row) {
//修改下时间,新浪的时间格式是这样的04-23 15:30
$time = date('y') . '-' . $row['time'] . ':00';
$sql .= "('{$row['url']}', '{$row['tit']}', '{$time}'),";
}
$sql = rtrim($sql, ',');
$ret = $db->exec($sql);
if ($ret !== false) {
echo "线程{$this->name}成功插入{$ret}条数据\n";
} else {
var_dump($db->errorinfo());
}
}
}
}
}
//抓取页面地址
$url = 'http://www.51sjk.com/Upload/Articles/1/0/261/261741_20210702001305056.php?ch=01#col=89&spec=&type=&ch=01&k=&offset_page=0&offset_num=0&num=60&asc=&page=';
//创建pool池
$pool = new pool(5, 'db', ['mysql:dbname=test;host=192.168.33.226', 'root', '']);
//获取100个分页数据
for ($ix = 1; $ix <= 100; $ix++) {
$pool->submit(new sina($ix, $url . $ix));
}
//循环收集垃圾,阻塞主线程,等待子线程结束
while ($pool->collect()) ;
$pool->shutdown();
由于使用到了querylist,大家可以通过composer进行安装。
composer require jaeger/querylist
不过安装的版本是3.2,在我的php7.2下会有问题,由于each()已经被废弃,所以修改下源码,each()全换成foreach()就好了。
运行结果如下:

数据也保存进了数据库

当然大家也可以再次通过url,拿到具体的页面内容,这里就不做演示了,有兴趣的可以自已去实现。
MrG37088382