gyaaniguy / pcrawl
PHP 网页爬取和抓取库。支持多种客户端,快速解析,调试以及各种选项的即时更改
0.10-alpha
2023-03-15 12:44 UTC
Requires
- php: >=7.4
- ext-curl: *
- ext-json: *
- gravitypdf/querypath: ^3.0
- guzzlehttp/guzzle: ^7.5
Requires (Dev)
- phpunit/phpunit: 7.*
This package is auto-updated.
Last update: 2024-09-12 20:59:53 UTC
README
PCrawl
PCrawl 是一个用于爬取和抓取网页的 PHP 库。
它支持多种客户端:curl,guzzle。提供调试、修改和解析响应的选项。
功能
- 快速创建自定义客户端。流畅地更改客户端和客户端选项,如用户代理,使用方法链。
- 可以使用可重用的回调函数修改响应。
- 使用不同的标准(如httpcode、regex等)调试响应。
- 使用 querypath 库解析响应。提供了一些便利函数。
- 流畅的 API。不同的调试器、客户端和响应修改对象可以即时更改!
完整示例
我们将尝试抓取一个坏页面,然后使用调试器检测,并最终更改客户端选项以正确抓取页面。
- 设置一些客户端
// simple clients. $gu = new GuzzleClient(); // Custom Client, that does not allow redirects. $uptightNoRedirectClient = new CurlClient(); $uptightNoRedirectClient->setRedirects(0); // disable redirects // Custom client - thin wrapper around curl class ConvertToHttpsClient extends CurlClient { public function get(string $url, array $options = []): PResponse { $url = str_replace('http://', 'https://', $url); return parent::get($url, $options); } }
- 让我们创建一些调试器对象
$redirectDetector = new ResponseDebug(); $redirectDetector->setMustNotExistHttpCodes([301, 302, 303, 307, 308]); $fullPageDetector = new ResponseDebug(); $fullPageDetector->setMustExistRegex(['#</html>#']);
开始抓取!
为了测试,我们将使用不支持重定向的客户端抓取页面,然后使用重定向检测器检测 301。如果是这样,我们更改客户端选项以支持重定向并再次抓取。
$req = new Request(); $url = "http://www.whatsmyua.info"; $req->setClient($uptightNoRedirectClient); $count = 0; do { $res = $req->get($url); $redirectDetector->setResponse($res); if ($redirectDetector->isFail()) { var_dump($redirectDetector->getFailDetail()); $uptightNoRedirectClient->setRedirects(1); $res = $req->get($url); } } while ($redirectDetector->isFail() && $count++ < 1);
使用全页面检测器检测页面是否正确。
然后使用解析器解析响应体
if ($fullPageDetector->setResponse($res)->isFail()) { var_dump($redirectDetector->getFailDetail()); } else { $parser = new ParserCommon($res->getBody()); $h1 = $parser->find('h1')->text(); $htmlClass = $parser->find('html')->attr('class'); }
注意:调试器、客户端、解析器可以重复使用。
详细使用说明
函数的使用可以分为几个部分
安装
- Composer
composer init # for new projects. composer config minimum-stability dev # Will be removed once stable. composer require gyaaniguy/pcrawl composer update include __DIR__ . '/vendor/autoload.php'; #in PHP
- github
git clone git@github.com:gyaaniguy/PCrawl.git # clone repo cd PCrawl composer update # update composer mv ../PCrawl /desired/location # Move dir to desired location. require __DIR__ . '../PCrawl/vendor/autoload.php'; #in PHP
待办事项列表
- 利用 guzzlehttp 的异步支持
标准
PSR-12
PHPUnit tests