php使用pthreads v3多线程实现抓取新浪新闻信息操作示例

时间:2022-07-27
本文章向大家介绍php使用pthreads v3多线程实现抓取新浪新闻信息操作示例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例讲述了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=utf8mb4 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 = QLQueryList::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://roll.news.sina.com.cn/s/channel.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,拿到具体的页面内容,这里就不做演示了,有兴趣的可以自已去实现。

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP进程与线程操作技巧总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。