【问题标题】:php-html-parser How to follow redirectsphp-html-parser 如何跟踪重定向
【发布时间】:2021-06-13 18:16:02
【问题描述】:

https://github.com/paquettg/php-html-parser 有人知道如何在这个库中遵循重定向吗? 例如:

require "vendor/autoload.php";
use PHPHtmlParser\Dom;
$dom = new Dom;
$dom->loadFromUrl($html);

【问题讨论】:

  • 以最简单的方式 - 通过使用不同的库来发出请求并获得最终结果,然后使用 loadStr 代替......
  • 或者在loadFromUrl调用中传入你自己的ClientInterface,并使用一个设置为自动跟随重定向的方法。
  • 正如@CBroe 指出的那样,他们依赖Guzzle Client 可以创建并传入以允许重定向,这是默认行为
  • 但是怎么做呢? @hppycoder 你能举个例子吗?
  • 哦,这很有趣!这并不像我们想象的那么简单,我现在正在努力。我将在下面详细说明我的答案

标签: php html-parsing


【解决方案1】:

版本:

  • guzzlehttp/guzzle: "7.2.0"
  • paquettg/php-html-parser: "3.1.1"

为什么库本身不允许重定向?

loadFromUrl方法有如下签名(当时是3.1.1)

    public function loadFromUrl(string $url, ?Options $options = null, ?ClientInterface $client = null, ?RequestInterface $request = null): Dom
    {
        if ($client === null) {
            $client = new Client();
        }
        if ($request === null) {
            $request = new Request('GET', $url);
        }

        $response = $client->sendRequest($request);
        $content = $response->getBody()->getContents();

        return $this->loadStr($content, $options);
    }

查看$response = $client->sendRequest($request); 行,它转到 Guzzle 的客户端 - https://github.com/guzzle/guzzle/blob/master/src/Client.php#L131

/**
* The HttpClient PSR (PSR-18) specify this method.
*
* @inheritDoc
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
   $options[RequestOptions::SYNCHRONOUS] = true;
   $options[RequestOptions::ALLOW_REDIRECTS] = false;
   $options[RequestOptions::HTTP_ERRORS] = false;

   return $this->sendAsync($request, $options)->wait();
}

$options[RequestOptions::ALLOW_REDIRECTS] = false; 将自动关闭重定向。无论您通过 Client 或 Request 传递什么,它都会自动关闭重定向。

如何使用库跟踪重定向

观察到 loadFromUrl 方法将发出请求并获得响应,然后使用 loadStr 我们将模仿相同但使用 Guzzle(因为它是库的依赖项)。

<?php
// Include the autoloader
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use PHPHtmlParser\Dom;

include_once("vendor/autoload.php");

$client = new Client();
try {
    // Showing the allow_redirects for verbosity sake. This is on by default with GuzzleHTTP clients.
    $request = $client->request('GET', 'http://theeasyapi.com', ['allow_redirects' => true]);

    // This would work exactly the same
    //$request = $client->request('GET', 'http://theeasyapi.com');
} catch(GuzzleException $e) {
    // Probably do something with $e
    var_dump($e->getMessage());
    exit;
}

$dom = new Dom();
$domExample = $dom->loadStr($request->getBody()->getContents());
foreach($domExample->find('a') as $link) {
    var_dump($link->text);
}

上面的代码将实例化一个新的 Guzzle 客户端,并向允许重定向的 URL 发出请求。本例中使用的网站是一个会 301 从非安全重定向到安全的网站。

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 2011-05-26
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2015-06-09
    相关资源
    最近更新 更多