softonic/laravel-intelligent-scraper

此包已被弃用,不再维护。未建议替代包。

无需了解网页HTML结构即可轻松抓取网页的服务。

0.0.21 2020-12-22 11:44 UTC

This package is auto-updated.

Last update: 2022-04-23 11:06:12 UTC


README

Laravel Intelligent Scraper

Latest Version Software License Build Status Coverage Status Quality Score Total Downloads Average time to resolve an issue Percentage of issues still open

此包提供了一种抓取解决方案,无需了解网页HTML结构,当检测到HTML结构发生变化时自动配置。这允许您在长时间内无需手动干预继续抓取。

安装

要安装,请使用composer

composer require softonic/laravel-intelligent-scraper

要发布抓取器配置,您可以使用

php artisan vendor:publish --provider="Softonic\LaravelIntelligentScraper\ScraperProvider" --tag=config

数据库迁移已注册在服务提供者中,因此您可以执行迁移命令以创建所需的表。

php artisan migrate

依赖项

此包依赖于goutte,而goutte依赖于guzzle,因此您可以自定义客户端以满足您的需求。此包的唯一要求是您必须在处理堆栈中包含http_error中间件。

示例

<?php

use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Goutte\Client as GoutteClient;
use App\MyMiddleware;

$client = new GoutteClient();
$stack = new HandlerStack();

$stack->setHandler(new CurlHandler());
$stack->push(MyMiddleware::getHandler(), 'my_middleware'); // Your custom middleware
$stack->push(Middleware::httpErrors(), 'http_errors'); // Required middleware for the package

$guzzleClient = new GuzzleClient(['handler' => $stack]);
$client->setClient($guzzleClient);

默认堆栈已经包含了http_errors中间件,所以您只需要在不使用默认堆栈的情况下执行此操作。

配置

初始设置有两种不同的选项。该包可以使用数据集进行配置,或使用XPath进行配置。两种方式都能产生相同的结果,但根据您的XPath知识,您可能会偏好其中一种。我们建议使用XPath配置方法。

基于数据集的配置

第一步是了解您想从页面获取哪些数据,因此您必须转到该页面并选择所有要抓取的文本、图像、元数据等,并对它们进行标记,以便告诉抓取器您想要什么。

以微软商店的一个示例来说明:

<?php
use Softonic\LaravelIntelligentScraper\Scraper\Models\ScrapedDataset;

ScrapedDataset::create([
    'url'  => 'https://test.c/p/my-objective',
    'type' => 'Item-definition-1',
    'data' => [
        'title'     => 'My title',
        'body'      => 'This is the body content I want to get',
        'images'    => [
            'https://test.c/images/1.jpg',
            'https://test.c/images/2.jpg',
            'https://test.c/images/3.jpg',
        ],
    ],
]);

在这个例子中,我们可以看到我们想要不同的字段,我们随意标记了它们。其中一些有多个值,因此我们可以从页面抓取物品列表。

使用此单个数据集,我们将能够训练我们的抓取器,并能够抓取具有相同结构的任何页面。由于页面通常根据不同的变量具有不同的结构,因此您应该添加不同的数据集,尝试覆盖尽可能多的页面变化。抓取器将无法抓取未包含在数据集中的页面变化。

你可以检查如何工作以了解更多关于内部结构的信息。

在下一节中,我们将更深入地探讨如何创建新的数据集以及有哪些可用选项。

数据集创建

数据集由urldata组成。

  • url部分很简单,你只需指出你获取数据的URL。
  • type部分为当前数据集提供了一个项目名称。这允许你定义多个类型。
  • variant标识页面变体。标识符是基于用于获取数据的xpath构建的sha1哈希值。
  • data部分是你指出想要获取的数据和分配你想要的标签的地方。数据可以是项目列表或单个项目。

一个基本的例子可以是:

<?php
use Softonic\LaravelIntelligentScraper\Scraper\Models\ScrapedDataset;

ScrapedDataset::create([
    'url'     => 'https://test.c/p/my-objective',
    'type'    => 'Item-definition-1',
    'variant' => '8ed10778a83f1266e7ffed90205f7fb61ddcdf78',
    'data'    => [
        'title'     => 'My title',
        'body'      => 'This is the body content I want to get',
        'images'    => [
            'https://test.c/images/1.jpg',
            'https://test.c/images/2.jpg',
            'https://test.c/images/3.jpg',
        ],
    ],
]);

在这个数据集中,我们希望将文本我的标题标记为标题,并且我们还有一个我们希望标记为图片的图片列表。通过这种方式,我们可以灵活地逐个选择项目或在列表中选取。

有时我们想要标记一些在HTML中不干净的文字,因为它可能包含不可见的字符,如\r\n。为了避免处理这种情况,数据集允许你添加正则表达式。

使用body字段的正则表达式示例

<?php
use Softonic\LaravelIntelligentScraper\Scraper\Models\ScrapedDataset;

ScrapedDataset::create([
    'url'  => 'https://test.c/p/my-objective',
    'type' => 'Item-definition-1',
    'variant' => '8ed10778a83f1266e7ffed90205f7fb61ddcdf78',
    'data' => [
        'title'     => 'My title',
        'body'      => regexp('/^Body starts here, but it is do long that.*$/si'),
        'images'    => [
            'https://test.c/images/1.jpg',
            'https://test.c/images/2.jpg',
            'https://test.c/images/3.jpg',
        ],
    ],
]);

通过这个更改,我们将确保即使body包含隐藏字符,我们也能检测到它。

重要爬虫会尝试在所有标签中找到文本,包括子标签,因此如果你定义了一个没有限制的正则表达式,例如例如/.*Body starts.*/,由于该文本在<html>元素的某个子元素中,你将在<html>元素中找到文本。因此请仔细定义正则表达式。

基于XPath的配置

在你从HTML收集了所有XPath之后,你只需创建配置模型。它们看起来像:

<?php
use Softonic\LaravelIntelligentScraper\Scraper\Models\Configuration;

Configuration::create([
    'name' => 'title',
    'type' => 'Item-definition-1',
    'xpaths' => '//*[@id=title]',
]);

Configuration::create([
    'name' => 'category',
    'type' => 'Item-definition-1',
    'xpaths' => ['//*[@id=cat]', '//*[@id=long-cat]'],
]);

在定义中,你应该为要爬取的字段提供一个名称,并标识其类型。xpaths字段可以包含一个字符串或一个字符串数组。这是因为HTML可以根据特定页面包含不同的变体,因此你可以编写一个Xpath列表,按顺序检查以获取第一个找到的结果。

用法

配置爬虫后,你将能够使用scrape助手请求特定的爬取。

<?php 

scrape('https://test.c/p/my-objective', 'Item-definition-1');

有一个名为context的可选参数,允许你为scrapeRequest设置上下文,这样你就可以在你的监听器中访问该上下文。这对于你需要在你的监听器中处理一些额外数据(除爬取数据之外)很有用。

<?php

scrape('https://test.c/p/my-objective', 'Item-definition-1', ['id' => 'my-objective']);

如果一切按预期进行,爬取将生成一个\Softonic\LaravelIntelligentScraper\Scraper\Events\Scraped事件。因此,请将监听器附加到该事件以接收数据。

$event->scrapeRequest->url;  // Url scraped
$event->scrapeRequest->type; // Request type
$event->scrapeRequest->context; // Context
$event->data; // Contains all the data in a [ 'fieldName' => 'value' ] format.
$event->variant; // Contains the page variation sha1 hash.

所有输出字段都是数组,可以包含一个或多个结果。

如果爬取失败,将触发一个带有爬取请求信息的\Softonic\LaravelIntelligentScraper\Scraper\Events\ScrapeFailed事件。

$event->scrapeRequest->url;  // Url scraped
$event->scrapeRequest->type; // Request type
$event->scrapeRequest->context; // Context

要附加监听器,你可以使用Laravel监听器配置,如:

// providers/EventServiceProvider
    protected $listen = [
        Scraped::class => [
            MyListener::class,
        ],
        ScrapeFailed::class => [
            MyListenerFirFailedScrapes::class,
        ],
    ];

但是,所有类型的抓取都将发送到该监听器。为了简化监听器,仅监听单一类型的抓取,在scraper.php中提供了一个listeners配置,因此您可以更精细地配置监听器。

    // config/scrapper.php
    'listeners' => [
        'scraped' => [
            'my-type-1' => ListenerForTypeOne::class,
            'my-type-2' => ListenerForTypeTwo::class,
        ],
        'scrape-failed' => [
            'my-type-1' => ListenerFailedForTypeOne::class,
        ],
    ];

高级用法

还有一个名为ConfigurationScraped的事件,在重新配置步骤中自动执行抓取时触发。它与Scraped事件完全相同。之所以名称不同,是因为通常不希望在内部之外使用它来更新数据集。

ConfigurationScraped可用于执行更新或了解配置过程内部细节。

队列工作者

您需要一个工作者,一个用于默认队列,另一个用于configure队列。为了防止并行配置,configure工作者应该是单个工作者。

php artisan queue:work # As many as you want
php artisan queue:work --queue=configure # Just one

测试

softonic/laravel-intelligent-scraper有一个PHPUnit测试套件和一个使用PHP CS Fixer的编码风格合规性测试套件。

要运行测试,请从项目文件夹运行以下命令。

$ docker-compose run test

要使用PsySH进行交互式运行

$ docker-compose run psysh

它是如何工作的?

抓取器是自动可配置的,但需要初始数据集或添加配置。数据集告诉配置器您需要哪些数据以及如何对其进行标记。

有三个服务具有独特职责,并使用事件系统连接。

抓取

它在系统接收到\Softonic\LaravelIntelligentScraper\Scraper\Events\ScrapeRequest事件时触发。可以使用我们的scrape($url, $type)辅助函数来完成此操作。

Scrape process

# Powered by https://code2flow.com/app
Scrape Request 'https://test.c/p/my-onjective' using 'Item-definition-1';
try {
  load configuration;
}
catch(Missing config) {
  goto fail;
}

extract data using configuration;
// It could be produced by old configuration
if(Error extracting data) {
  goto fail
}

fire Scraped Event;
return;

fail:
fire InvalidConfiguration Event;

更新数据集

为了可重新配置并保持数据集的新鲜度,抓取器会自动存储最新抓取的数据。

Updatge dataset process

# Powered by https://code2flow.com/app
Receive Scraped event;
Remove oldest scraped data;
Store scraped data;
Scrape dataset updated;

配置抓取器

如果发生InvalidConfiguration事件,系统将尝试计算新的配置以从ScrapeRequest获取信息。

Configuration process

# Powered by https://code2flow.com/app
Invalid Configuration for ScrapeRequest;

try {
  calculate configuration;
}
catch(Cannot be reconfigured) {
  goto fail;
}

extract data using configuration;
if(Error extracting data) {
  goto fail;
}

Store new configuerion;
Scraped data;
return;
fail:
Fire ScrapeFailed Event;
No scraped data;

此过程可能产生两个不同的事件

  • Scraped:所有工作都按预期进行,页面已抓取
  • ScrapeFailed:重新计算配置后无法进行抓取,因此我们需要手动配置操作来修复它。

许可协议

Apache 2.0许可协议。有关更多信息,请参阅LICENSE