awam/se

根据关键词获取一些页面的元数据

v0.4 2022-07-01 20:56 UTC

This package is auto-updated.

Last update: 2024-09-29 06:09:11 UTC


README

在这个项目中,我们将模拟普通用户执行搜索操作以获取一组网站。然后我们将进入可用的页面并提取一些元数据。为了应用模拟过程,我们将

  1. 搜索所需的 keywords 并提取有用的链接。
  2. 对于每个链接,获取与其关联的元数据。

有多个库可以使用 PHP 进行抓取,例如 Guzzle、Guette、SimpleHtmlDom 或 Panther。在这个应用中,我们使用了 Symphony Panther 客户端,因为它适合使用ajax、axios库来获取数据的动态页面。但 Symphony Panther 需要chrome/firefox驱动来充当浏览器。在开始 panther 应用之前,我们需要安装驱动。

要配置 Symphony Panther,我们执行以下操作

  1. 安装 chrome 驱动

composer require --dev dbrekelmans/bdi && vendor/bin/bdi detect drivers 2. 安装执行该任务的包。 composer require awam/se

awam/se 包托管在 https://packagist.org.cn/

安装包后,我们可以创建 index.php 文件。如果我们想查找像 red 这样的关键词,我们可以执行此片段


use HttpClient\PantherClient;

require "vendor/autoload.php";

/**
 * In order to try many HttpClients, such as (Guzzle, Goutte, SimpleHtmlDom, or Panther), we need loose coupling
 * between Search Engine and Http Clients, so we have used service container (Dependency Injection) in this case.
 * In this application, we used Symphony Panther client as it is suitable for dynamic pages that uses ajax, axios libraries to get their data.
 */


$httpClient = new HttpClient\PantherClient();

$client = new SearchEngine\SearchEngine($httpClient);
$client->setEngine('google.ae');
$results = $client->search(['red']);

while ($results->valid()) {
    var_dump("\n==================\n");
    var_dump($results->current());
    $results->next();
}

之后,我们可以在 cmd 中运行命令

php index.php

注意,$results 是 ArrayIterator,我们可以在链接之间进行遍历。由于在 SearchEngine 和 PantherClient 之间实现了依赖注入,该项目可以轻松扩展以适应其他 Http Clients。