giauphan/goutte-facade

Goutte 的 Laravel Facade,一个简单的 PHP 网络爬虫

v1.0 2024-03-14 02:24 UTC

This package is auto-updated.

Last update: 2024-09-14 03:31:25 UTC


README

此存储库实现了一个简单的 ServiceProvider,它通过 Laravel 中的 Facade 使 Goutte 客户端的单例实例易于访问。有关 PHP 网络爬虫及其接口的更多信息,请参阅 @FriendsOfPHP/Goutte

警告

Goutte 已弃用,建议使用 Symfony HttpBrowserBrowserKit 组件中直接替换。此包是为 Laravel 应用程序开发的一个简单集成,因此也将被弃用。

使用 Composer 安装

在您的终端应用程序中使用 cd 命令将目录更改为您的 Laravel 项目的根目录,并使用 composer 将项目作为依赖项添加。

$ cd ~/Sites/laravel-example-project
$ composer require giauphan/goutte

这将向您的 composer.json 添加以下行,并将项目及其依赖项下载到您的项目 ./vendor 目录中

// ./composer.json
{
    "name": "giauphan/laravel-goutte-test",
    "description": "A dummy project used to test the Laravel Goutte Facade.",

    // ...

    "require": {
        "php": "^7.2",
        "laravel/framework": "^8",
        "giauphan/goutte": "^2",
        // ...
    },

    //...
}

用法

为了使用静态接口,我们首先需要自定义应用程序配置,告诉系统它可以在哪里找到新的服务。在您选择的编辑器中打开文件 config/app.php,并添加以下行(《[1]》和《[2]》)

// config/app.php

return [

    // ...

    'providers' => [

        // ...

        /*
         * Package Service Providers...
         */
        giauphan\Goutte\GoutteServiceProvider::class, // [1] This will register the Package in the laravel echo system

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

    ],

    // ...

    'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,

        // ...

        'Goutte' => giauphan\Goutte\GoutteFacade::class, // [2] It will register as an alias for the Goutte facade
        'Hash' => Illuminate\Support\Facades\Hash::class,

        // ...
    ],

];

现在您应该能够在应用程序中使用 facade。一旦使用已注册的别名,Laravel 将自动加载相应的类。

// routes/web.php

Route::get('/', function() {
    $crawler = Goutte::request('GET', 'https://duckduckgo.com/html/?q=Laravel');
    $crawler->filter('.result__title .result__a')->each(function ($node) {
      dump($node->text());
    });
    return view('welcome');
});

提示: 如果您检索到 "未找到类 'Goutte' "-异常,请尝试在项目根目录中运行 composer dump-autoload 以更新自动加载器。

提示: 您还可以使用 Lumen。在 bootstrap/app.php 中注册 GoutteServiceProvider,并在 AppServiceProvider 中提供配置目录的缺失路径(参看《[34]》)。

配置

您可以根据需要自定义默认请求选项以应用于客户端的每个请求。首先将默认配置复制到您的应用程序目录中

php artisan vendor:publish --provider="giauphan\Goutte\GoutteServiceProvider"

config/goutte.php 中打开创建的文件,并根据您的喜好自定义配置选项。

<?php

return [
    'client' => [
        'max_redirects' => 0,
    ],
];

请参阅 Symfony Http Client 文档 了解完整选项列表。

版本约束