php也可以寫爬蟲
- 說起爬蟲,大多數第一反應都是python,python強大的requests和bs4等等強大的第三方庫讓人們都喜歡用python去寫爬蟲。但是php作為“世界上最好的語言”當然也可以用來開發爬蟲。
- 寫了一個小的爬蟲爬取社群的文章原始碼地址
前期準備
- composer
- Guzzle Guzzle是一個十分強大的php的模擬HTTP client的第三方庫,可以通過composer安裝
- Goutte Goutte是一個用來解析HTML文件的第三方庫,可以通過composer安裝
開始工作
1.安裝兩個庫
- Goutte
composer require fabpot/goutte
- Guzzle
composer require guzzlehttp/guzzle:~6.0
2.建立命令
php artisan make:command Spider
3.命令引數
protected $signature = 'command:spider {concurrency} {keyWords*}'; //concurrency為併發數 keyWords為查詢關鍵詞
4.編寫爬蟲
- 寫了一個簡單的,主要用來爬取社群的文章,通過命令列引數獲取要搜尋的關鍵詞,然後爬取文章,並爬下內容存在本地。直接貼程式碼啦。
<?php
namespace App\Console\Commands;
use Goutte\Client as GoutteClient;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Pool;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class Spider extends Command
{
protected $signature = 'command:spider {concurrency} {keyWords*}'; //concurrency為併發數 keyWords為查詢關鍵詞
protected $description = 'php spider';
public function __construct()
{
parent::__construct();
}
public function handle()
{
//
$concurrency = $this->argument('concurrency'); //併發數
$keyWords = $this->argument('keyWords'); //查詢關鍵詞
$guzzleClent = new GuzzleClient();
$client = new GoutteClient();
$client->setClient($guzzleClent);
$request = function ($total) use ($client,$keyWords){
foreach ($keyWords as $key){
$url='https://laravel-china.org/search?q='.$key;
yield function () use($client,$url){
return $client->request('GET',$url);
};
}
};
$pool = new Pool($guzzleClent,$request(count($keyWords)),[
'concurrency' => $concurrency,
'fulfilled' => function ($response, $index) use ($client){
$response->filter('h2 > a')->reduce(function($node) use ($client){
if(strlen($node->attr('title'))==0) {
$title = $node->text(); //文章標題
$link = $node->attr('href'); //文章連結
$carwler = $client->request('GET',$link); //進入文章
$content=$carwler->filter('#emojify')->first()->text(); //獲取內容
Storage::disk('local')->put($title,$content); //儲存在本地
}
});
},
'rejected' => function ($reason, $index){
$this->error("Error is ".$reason);
}
]);
//開始爬取
$promise = $pool->promise();
$promise->wait();
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結