You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Goutte爬虫超时失效,遇Too many redirects无响应

解决Goutte爬虫遇到Too many redirects时冻结的问题

针对你遇到的爬虫因目标网站重定向循环冻结的问题,可通过以下几个步骤调整配置来解决:

1. 修正HttpClient的重定向与超时配置

Symfony HttpClient的重定向规则需明确配置在allow_redirects数组中(部分版本顶级参数max_redirects可能不生效),同时区分连接超时与总请求超时,确保请求在超时或重定向超限后及时终止:

use Goutte\Client;
use Symfony\Component\HttpClient\HttpClient;

try {
    $httpClient = HttpClient::create([
        // 总请求超时(包含所有重定向流程)
        'timeout' => 5,
        // 初始连接超时
        'connect_timeout' => 3,
        // 明确配置重定向规则
        'allow_redirects' => [
            'max' => 1, // 最大重定向次数
            'strict' => true, // 禁止HTTPS转HTTP等不安全重定向
            'protocols' => ['https'], // 仅允许HTTPS协议重定向
        ],
    ]);
    
    $client = new Client($httpClient);
    $response = $client->request('GET', 'https://' . $domain_name);
} catch (\Exception $e) {
    $this->error($e->getMessage());
}

2. 添加重定向监控回调强制终止循环

若上述配置仍未生效,可通过on_progress回调实时跟踪重定向次数,一旦超过限制立即抛出异常终止请求:

use Goutte\Client;
use Symfony\Component\HttpClient\HttpClient;

try {
    $redirectCount = 0;
    
    $httpClient = HttpClient::create([
        'timeout' => 5,
        'connect_timeout' => 3,
        'allow_redirects' => [
            'max' => 1,
            'track_redirects' => true, // 开启重定向跟踪
        ],
        'on_progress' => function (int $dlNow, int $dlSize, array $info) use (&$redirectCount) {
            $currentRedirects = $info['redirect_count'] ?? 0;
            if ($currentRedirects > 1) {
                throw new \RuntimeException('触发重定向循环,已终止请求');
            }
        },
    ]);
    
    $client = new Client($httpClient);
    $response = $client->request('GET', 'https://' . $domain_name);
} catch (\Exception $e) {
    $this->error($e->getMessage());
}

3. 排查版本兼容性

若问题持续,检查当前使用的Goutte和Symfony HttpClient版本是否匹配,部分旧版本可能存在重定向处理bug,建议升级至稳定版本(Goutte >= 4.0,Symfony HttpClient >= 5.4)。

内容的提问来源于stack exchange,提问作者slame1121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 02:31:08