爬取糗事百科熱門列表頁,采用守護(hù)進(jìn)程模式。在開始爬取前,我們需要一個(gè)隊(duì)列,在這里使用框架中帶有的內(nèi)存隊(duì)列。
首先建立一個(gè)隊(duì)列文件 queue.php,寫入下列內(nèi)容
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// 啟動(dòng)隊(duì)列
\Beanbun\Queue\MemoryQueue::server();
建立爬蟲文件 start.php,寫入下列內(nèi)容
<?php
use Beanbun\Beanbun;
use Beanbun\Lib\Helper;
require_once(__DIR__ . '/vendor/autoload.php');
$beanbun = new Beanbun;
$beanbun->name = 'qiubai';
$beanbun->count = 5;
$beanbun->seed = 'http://www.qiushibaike.com/';
$beanbun->max = 30;
$beanbun->logFile = __DIR__ . '/qiubai_access.log';
$beanbun->urlFilter = [
'/http:\/\/www.qiushibaike.com\/8hr\/page\/(\d*)\?s=(\d*)/'
];
// 設(shè)置隊(duì)列
$beanbun->setQueue('memory', [
'host' => '127.0.0.1',
'port' => '2207'
]);
$beanbun->afterDownloadPage = function($beanbun) {
file_put_contents(__DIR__ . '/' . md5($beanbun->url), $beanbun->page);
};
$beanbun->start();
接下來在命令行中執(zhí)行
$ php queue.php start
$ php start.php start
先啟動(dòng)隊(duì)列進(jìn)程,再啟動(dòng)爬蟲。
更多建議: