evgeek/scraperapi-sdk

scraperapi.com 的 SDK

v0.4.0 2021-12-14 19:34 UTC

This package is auto-updated.

Last update: 2024-09-19 20:22:54 UTC


README

使用 ScraperAPI 简化您的网络抓取任务。此 SDK 与 Guzzle 客户端 兼容,提供异步多线程请求和方便的 PSR-7 响应。

安装

需要 PHP 版本 7.2 或更高

$ composer require evgeek/scraperapi-sdk

基本用法

<?php

use Evgeek\Scraperapi\Client;

require '/path/to/you/vendor/autoload.php';

//Create and configure a new SDK client
$sdk = new Client('YOUR_TOKEN');

//Send request
$response = $sdk->get('https://example.com');

//Work with \Psr\Http\Message\ResponseInterface
echo $response->getBody()->getContents();

设置客户端

客户端通过构造函数参数进行配置

  • $apiKey (必需) - 来自 ScraperAPI 控制台 的 API 密钥。
  • $defaultApiParams - 请求的默认 API 参数
  • $defaultHeaders - 默认 HTTP 标头
  • $timeout (默认 60) - 请求超时。
  • $tries (默认 3) - 请求尝试次数。
  • $delayMultiplier (默认 1) - 新请求尝试之前的延迟倍数(秒)。倍数 3 表示第二次尝试将在 3 秒后进行,第三次尝试将在 6 秒后进行,依此类推。
  • $printDebugInfo (默认 false) - 如果为真,则打印调试信息。对于调试异步请求很有用。
  • $showApiKey (默认 false) - 如果为假,则调试信息中的 API 密钥将被替换为 'API_KEY' 字符串。
  • $logger (默认 null) - PSR-3 兼容的日志记录器,用于调试信息。如果为 null,则将发送到 STDIN。
  • $logLevel (默认 null) - PSR-3 日志记录器的日志级别。如果为 null,则调试信息将发送到 DEBUG 级别。
  • $maxExceptionsLength (默认 120) - Guzzle 异常消息的最大长度。

配置默认 SDK 客户端参数

API 参数

根据 ScraperAPI 文档 配置默认 API 功能。默认设置适用于所有请求,除非在请求级别中覆盖。您只能从构造函数(SDK 客户端不可变)设置默认选项,使用第二个参数

$defaultApiParams = [
    'country_code' => 'us', //activate country geotargetting
    'render' => true, //activate javascript rendering
    'premium' => false, //activate premium residential and mobile IPs
    'session_number' => 123, //reuse the same proxy
    'keep_headers' => true, //use your own custom headers
    'device_type' => 'mobile', //set mobile or desktop user agents
    'autoparse' => 'false', //activate auto parsing for select websites
];
$sdk = new Client('YOU_TOKEN', $defaultApiParams);

标头

您可以使用构造函数的第三个参数添加默认标头。别忘了启用 keep_headers 允许您的标头被使用!

$defaultHeaders = [
    'Referer' => 'https://example.com/',
    'Accept' => 'application/json',
];
$sdk = new Client('YOU_TOKEN', ['keep_headers' => true], $defaultHeaders);

请求

SDK 支持 GETPOSTPUT HTTP 方法。每个请求方法的常规参数

  1. $url (必需) - 被抓取资源的 URL。
  2. $apiParams (默认 null) - 设置请求的 API 设置。它们将覆盖 SDK 客户端的默认设置(仅重叠的设置)。
  3. $headers (默认 null) - 设置请求的标头。就像 $apiParams 一样,它们将覆盖 SDK 客户端的默认设置(仅重叠的设置)。

同步

GET

非常简单

$response = $sdk->get(
    'https://example.com', 
    ['keep_headers' => true], 
    [
        'Referer' => 'https://example.com/',
        'Accept' => 'application/json',
    ]
);
$content = $response->getBody()->getContents();

POST/PUT

稍微复杂一些

$response = $sdk->post('https://example.com', $apiParams, $headers, $body, $formParams, $json);
$content = $response->getBody()->getContents();

您可以使用三种类型的有效负载

  • $body 用于原始 stringfopen() 资源或 Psr\Http\Message\StreamInterface
  • $formParams - 用于表单数据。关联 array 的表单字段名到值,其中每个值都是字符串或字符串数组。
  • $json - 用于JSON。传入的关联数组(array)将被自动转换为JSON数据。

不同类型的有效负载也有方法的简写形式

$response = $sdk->postBody($url, $body, $apiParams, $headers);
$response = $sdk->postForm($url, $formParams, $apiParams, $headers);
$response = $sdk->postJson($url, $json, $apiParams, $headers);

顺便说一下,通过$json传递GraphQL有效负载很方便

$query = '
    query HeroNameAndFriends($episode: Episode) {
      hero(episode: $episode) {
        name
        friends {
          name
        }
      }
    }
';
$json = ['query' => $query, 'variables' => ['episode' => 'JEDI']];

$response = $sdk->postJson('https://example.com', $json);

异步

一切都与同步相似,但工作不是通过请求,而是通过承诺(promises)进行的

//Create array with promises
$promises = [
    'first' => $sdk->getPromise('https://example.com', ['country_code' => 'us']),
    'second' => $sdk->postPromiseBody('https://example.com', 'payload'),
];
//Asynchronous fulfillment of promises
$responses = $sdk->resolvePromises($promises);

//Work with array of responses
foreach ($responses as $response) {
    echo $response->getBody()->getContents() . PHP_EOL;
}

您的ScraperAPI账户信息

您可以使用accountInfo()方法获取您的ScraperAPI账户信息

$info = $sdk->accountInfo();
var_dump(json_decode($info, true));
array(5) {
  ["concurrencyLimit"]=>
  int(5)
  ["concurrentRequests"]=>
  int(0)
  ["failedRequestCount"]=>
  int(258)
  ["requestCount"]=>
  int(588)
  ["requestLimit"]=>
  string(4) "1000"
}