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
相关产品推荐
相关产品推荐

