coooold/crawler
Composer 安装命令:
composer require coooold/crawler
包简介
Most powerful, popular and production crawling/scraping package for PHP
README 文档
README
Most powerful, popular and production crawling/scraping package for PHP, happy hacking :)
Features:
- server-side DOM & automatic DomParser insertion with Symfony\Component\DomCrawler
- Configurable pool size and retries
- Control rate limit
- forceUTF8 mode to let crawler deal for you with charset detection and conversion
- Compatible with PHP 7.2
Thanks to
- Amp a non-blocking concurrency framework for PHP
- Artax An Asynchronous HTTP Client for PHP
- node-crawler Most powerful, popular and production crawling/scraping package for Node
node-crawler is really a great crawler. PHPCrawler tries its best effort to keep similarity with it.
Table of Contents
Get started
Install
$ composer require "coooold/crawler"
Basic usage
use PHPCrawler\PHPCrawler; use PHPCrawler\Response; use Symfony\Component\DomCrawler\Crawler; $logger = new Monolog\Logger("fox"); try { $logger->pushHandler(new \Monolog\Handler\StreamHandler(STDOUT, \Monolog\Logger::INFO)); } catch (\Exception $e) { } $crawler = new PHPCrawler([ 'maxConnections' => 2, 'domParser' => true, 'timeout' => 3000, 'retries' => 3, 'logger' => $logger, ]); $crawler->on('response', function (Response $res) use ($cli) { if (!$res->success) { return; } $title = $res->dom->filter("title")->html(); echo ">>> title: {$title}\n"; $res->dom ->filter('.related-item a') ->each(function (Crawler $crawler) { echo ">>> links: ", $crawler->text(), "\n"; }); }); $crawler->queue('https://www.foxnews.com/'); $crawler->run();
Slow down
Use rateLimit to slow down when you are visiting web sites.
$crawler = new PHPCrawler([ 'maxConnections' => 10, 'rateLimit' => 2, // reqs per second 'domParser' => true, 'timeout' => 30000, 'retries' => 3, 'logger' => $logger, ]); for ($page = 1; $page <= 100; $page++) { $crawler->queue([ 'uri' => "http://www.qbaobei.com/jiaoyu/gshb/List_{$page}.html", 'type' => 'list', ]); } $crawler->run(); //between two tasks, avarage time gap is 1000 / 2 (ms)
Custom parameters
Sometimes you have to access variables from previous request/response session, what should you do is passing parameters as same as options:
$crawler->queue([ 'uri' => 'http://www.google.com', 'parameter1' => 'value1', 'parameter2' => 'value2', ])
then access them in callback via $res->task['parameter1'], $res->task['parameter2'] ...
Raw body
If you are downloading files like image, pdf, word etc, you have to save the raw response body which means Crawler shouldn't convert it to string. To make it happen, you need to set encoding to null
$crawler = new PHPCrawler([ 'maxConnections' => 10, 'rateLimit' => 2, // req per second 'domParser' => false, 'timeout' => 30000, 'retries' => 3, 'logger' => $logger, ]); $crawler->on('response', function (Response $res, PHPCrawler $crawler) { if (!$res->success) { return; } echo "write ".$res->task['fileName']."\n"; file_put_contents($res->task['fileName'], $res->body); }); $crawler->queue([ 'uri' => "http://www.gutenberg.org/ebooks/60881.txt.utf-8", 'fileName' => '60881.txt', ]); $crawler->queue([ 'uri' => "http://www.gutenberg.org/ebooks/60882.txt.utf-8", 'fileName' => '60882.txt', ]); $crawler->queue([ 'uri' => "http://www.gutenberg.org/ebooks/60883.txt.utf-8", 'fileName' => '60883.txt', ]); $crawler->run();
Events
Event::RESPONSE
Triggered when a request is done.
$crawler->on('response', function (Response $res, PHPCrawler $crawler) { if (!$res->success) { return; } });
Event::DRAIN
Triggered when queue is empty.
$crawler->on('drain', function () { echo "queue is drained\n"; });
Advanced
Encoding
HTTP body will be converted to utf-8 from the default encoding.
$crawler = new PHPCrawler([ 'encoding' => 'gbk, ]);
Logger
A PSR logger instance could be used.
$logger = new Monolog\Logger("fox"); $logger->pushHandler(new \Monolog\Handler\StreamHandler(STDOUT, \Monolog\Logger::INFO)); $crawler = new PHPCrawler([ 'logger' => $logger, ]);
See Monolog Reference.
Coroutine
PHPCrawler, based on amp non-blocking concurrency framework, could work with coroutines, ensuring excellent performance. Amp async packages should be used in callbacks, that is to say, neither php native mysql client nor php native file io is not recommended. The keyword yield like await in ES6, introduced the non-blocking io.
$crawler->on('response', function (Response $res) use ($cli) { /** @var \Amp\Artax\Response $res */ $res = yield $cli->request("https://www.foxnews.com/politics/lindsey-graham-adam-schiff-is-doing-a-lot-of-damage-to-the-country-and-he-needs-to-stop"); $body = yield $res->getBody(); echo "=======> body " . strlen($body) . " bytes \n"; });
Work with DomParser
Symfony\Component\DomCrawler is a handy tool for crawling pages. Response::dom will be injected with an instance of Symfony\Component\DomCrawler\Crawler.
$crawler->on('response', function (Response $res) use ($cli) { if (!$res->success) { return; } $title = $res->dom->filter("title")->html(); echo ">>> title: {$title}\n"; $res->dom ->filter('.related-item a') ->each(function (Crawler $crawler) { echo ">>> links: ", $crawler->text(), "\n"; }); });
See DomCrawler Reference.
Other
coooold/crawler 适用场景与选型建议
coooold/crawler 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 30 次下载、GitHub Stars 达 1, 最近一次更新时间为 2019 年 12 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「spider」 「crawler」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 coooold/crawler 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 coooold/crawler 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 coooold/crawler 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A lightweight, dependency free PHP class that acts as wrapper for Crawlbase API
Sitemap crawler/generator. For the given URL it will return sitemap XML file with URLs and images.
A new generation of multi-process async event-driven spider engine based on Workerman
X-Robots-Tag HTTP header parser class
parser/handler for Robots Exclusion Protocol (robots.txt and more)
统计信息
- 总下载量: 30
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2019-12-10