php爬虫框架Goutte
Github: https://github.com/FriendsOfPHP/Goutte
Goutte提供了很友好的API用来抓取网页并提取数据,和php项目直接对接,非常简单和强大。
运行环境
- PHP 5.5+ 、Guzzle 6+
- 支持PHP 5.4、Guzzle 4-5, 请使用Goutte 2.x (latest phar)
- 支持PHP 5.3 or Guzzle 3, 请使用Goutte 1.x (latest phar)
安装方法
composer require fabpot/goutte
如果你选择的是phar版的只需要下载好文件后在你的项目中require进去就可以了,无需使用composer安装。
使用方法
创建客户端实例(Symfony\Component\BrowserKit\Client):
use Goutte\Client; $client = new Client();
使用request()方法发起页面请求
// Go to the symfony.com website
$crawler = $client->request('GET', 'https://www.symfony.com/blog/');该方法会返回一个Crawler对象(Symfony\Component\DomCrawler\Crawler).
Goutte依赖Guzzle,如果要自己配置Guzzle参数的话你可以为Goutte创建一个Guzzle实例,下面我们要做一个60秒请求超时时间,并且无需验证ssl的设定:
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
'timeout' => 60,
'verify' => false, //官方example中没有这项,这个还是很必要的,不然在请求有些https站点的时候会出错,我已填坑
));
$goutteClient->setClient($guzzleClient);点击链接
// Click on the "Security Advisories" link
$link = $crawler->selectLink('Security Advisories')->link();
$crawler = $client->click($link);提取数据
// Get the latest post in this category and display the titles
$crawler->filter('h2 > a')->each(function ($node) {
print $node->text()."\n";
});表单提交
$crawler = $client->request('GET', 'https://github.com/');
$crawler = $client->click($crawler->selectLink('Sign in')->link());
$form = $crawler->selectButton('Sign in')->form();
$crawler = $client->submit($form, array('login' => 'fabpot', 'password' => 'xxxxxx'));
$crawler->filter('.flash-error')->each(function ($node) {
print $node->text()."\n";
});相关文档
阅读文档BrowserKit和DomCrawler的相关组件有利于你更好的使用Goutte.
技术依赖
Goutte依赖于这些牛X的PHP库:
- Symfony组件: BrowserKit, CssSelector, DomCrawler;
- Guzzle HTTP组件.