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 = 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://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使用pthreads v3多线程的抓取新浪新闻信息的更多相关文章
- 【转】Python爬虫:抓取新浪新闻数据
案例一 抓取对象: 新浪国内新闻(http://news.sina.com.cn/china/),该列表中的标题名称.时间.链接. 完整代码: from bs4 import BeautifulSou ...
- Python爬虫:抓取新浪新闻数据
案例一 抓取对象: 新浪国内新闻(http://news.sina.com.cn/china/),该列表中的标题名称.时间.链接. 完整代码: from bs4 import BeautifulSou ...
- Python抓取新浪新闻数据(二)
以下是抓取的完整代码(抓取了网页的title,newssource,dt,article,editor,comments)举例: 转载于:https://blog.51cto.com/2290153/ ...
- python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例
python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例 新浪爱彩双色球开奖数据URL:http://zst.aicai.com/ssq/openInfo/ 最终输出结果格 ...
- selenium+BeautifulSoup+phantomjs爬取新浪新闻
一 下载phantomjs,把phantomjs.exe的文件路径加到环境变量中,也可以phantomjs.exe拷贝到一个已存在的环境变量路径中,比如我用的anaconda,我把phantomjs. ...
- python3爬虫-爬取新浪新闻首页所有新闻标题
准备工作:安装requests和BeautifulSoup4.打开cmd,输入如下命令 pip install requests pip install BeautifulSoup4 打开我们要爬取的 ...
- python抓取新浪首页的小例子
参考 廖雪峰的python教程:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0 ...
- Python爬虫:新浪新闻详情页的数据抓取(函数版)
上一篇文章<Python爬虫:抓取新浪新闻数据>详细解说了如何抓取新浪新闻详情页的相关数据,但代码的构建不利于后续扩展,每次抓取新的详情页时都需要重新写一遍,因此,我们需要将其整理成函数, ...
- Python 抓取网页并提取信息(程序详解)
最近因项目需要用到python处理网页,因此学习相关知识.下面程序使用python抓取网页并提取信息,具体内容如下: #---------------------------------------- ...
随机推荐
- How to Pronounce Numbers 11 – 19
How to Pronounce Numbers 11 – 19 Share Tweet Share Tagged With: Numbers Numbers are something you’ll ...
- form表单 获取与赋值
form表单中使用频繁的组件: 文本框.单选框.多选框.下拉框.文本域form通过getValues()获取表单中所有name的值 通过setValues({key:values})给对应的name值 ...
- HttpURLConnection 添加代理
//创建代理服务器 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("www.proxyaddress.com& ...
- C# 获取汉字转拼音缩写-简写,不是全拼
///<summary> /// 汉字转拼音缩写 /// Code By ] -'\0')); if ( i <0xB0A1) return"*" ...
- 吴裕雄 python 爬虫(1)
from urllib.parse import urlparse url = 'http://www.pm25x.com/city/beijing.htm' o = urlparse(url) pr ...
- 吴裕雄 12-MySQL WHERE 子句
以下是 SQL SELECT 语句使用 WHERE 子句从数据表中读取数据的通用语法:SELECT field1, field2,...fieldN FROM table_name1, table_n ...
- gdb 常用调试命令
1. file quit 2. frame bt 3. finish 运行程序,直到当前函数完成返回,并打印函数返回时的堆栈地址和返回值及参数信息. until 当要退出在一个循环体 ...
- AngularJS 中{{}}与ng-bind指令
面试中,有被问题关于{{}}与ng-bind指令的问题,在此,分享下自己的知识点. 在脚本没有加载完成时,用户会看到{{}},界面比较丑陋. 一般的解决方法: 在index.html里面使用n ...
- JS拖拽元素原理及实现代码
一.拖拽的流程动作 ①鼠标按下②鼠标移动③鼠标松开 二.拖拽流程中对应的JS事件 ①鼠标按下会触发onmousedown事件 ②鼠标移动会触发onmousemove事件 ③鼠标松开会触发onmouse ...
- 在Laravel外独立使用laravel-mongodb
laravel框架外部使用laravel-mongodb 插件 下载安装方式主要根据github上的参考: https://github.com/jenssegers/laravel-mongodb# ...