ssola/crawly

此包的最新版本(1.0.0)没有可用的许可证信息。

简单的网络爬虫库

1.0.0 2014-11-18 21:57 UTC

This package is not auto-updated.

Last update: 2024-09-24 08:33:02 UTC


README

Crawly 是一个简单的网络爬虫,能够根据发现的内容提取和跟进链接。

简单示例

require_once("vendor/autoload.php");

// Create a new Crawly object
$crawler = Crawly\Factory::generic();

// Discovers are allows you to extract links to follow
$crawler->attachDiscover(
    new Crawly\Discovers\CssSelector('nav.pagination > ul > li > a')
);

// After we scrapped and discovered links you can add your own closures to handle the data
$crawler->attachExtractor(
    function($response) {
        // here we have the response, work with it!
    }
);

// set seed page
$crawler->setSeed("http://www.webpage.com/test/");

// start the crawler
$crawler->run();

爬虫对象

您可以使用爬虫工厂创建一个简单的爬虫,它将使用 Guzzle 作为 HTTP 客户端生成一个 Crawly 对象。

$crawler = Crawly\Factory::generic();

您可以创建一个个性化的爬虫,指定要使用的 HTTP 客户端、URL 队列和已访问链接集合。

$crawler = Crawly\Factory::create(new MyHttpClass(), new MyUrlQueue(), new MyVisitedCollection());

发现

发现用于从 HTML 中提取一组要包含到队列中的链接。您可以包含任意数量的发现,也可以创建自己的发现类。

目前 Crawly 只包含一个 CSS 选择器发现。

创建自己的发现

只需创建一个新的类,该类实现 Discoverable 接口。这个新类应该看起来像以下示例

class MyOwnDiscover implements Discoverable
{
    private $configuration;

    public function __construct($configuration) 
    {
        $this->configuration = $configuration;
    }

    public function find(Crawly &$crawler,  $response)
    {
        // $response has the crawled url content
        // do some magin on the response and get a colleciton of links
        
        foreach($links as $node) {
            $uri = new Uri($node->getAttribute('href'), $crawler->getHost());

            // if url was not visited we should include this new links to the Url Queue
            if(!$crawler->getVisitedUrl()->seen($uri->toString())) {
                $crawler->getUrlQueue()->push($uri);
            }
        }
    }
}

限制器

限制器用于限制爬虫的操作。例如,我们可以限制可以爬取的链接数量或最大带宽使用量。

提取器