Guzzle 7 - 403 禁止(适用于 CURL)

Guzzle 7 - 403 Forbidden (works fine with CURL)

更新:似乎 user-agent 并不是唯一的 header 一些主机需要服务 HTML,我还必须添加 'accepts' header,最后这解决了我与许多主机的问题:

  $response = $client->request('GET', 'http://acme.com', ['headers' => ['user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36',
'accept'=> 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
        ]]);

我正在尝试使用 Guzzle 检索某些网站,但收到 403 禁止错误(当它们在浏览器中正常工作时),我怀疑这是由于 non-standard User-Agents 被主机禁止。为了解决这个问题,我试图在 Guzzle 中设置 User-Agent 来模仿浏览器,但我找不到任何实际有效的方法。我可以浏览该网站,也可以使用 WGET 和 CURL -L 下载 HTML 没有问题,所以问题似乎出在 Guzzle.

我试过:

    $client = new Client(['allow_redirects' => ['track_redirects' => true]]);
    $client->setUserAgent("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36");
    $response = $client->get($domain_name);

奇怪的是,这个 ^ 导致一个错误,似乎说 Guzzle 正在尝试浏览到 User-Agent 值:cURL 错误 6:无法解析主机:Mozilla (参见 https://curl.haxx.se/libcurl/c/libcurl-errors.html)对于 Mozilla/5.0%20(Windows%20NT%206.2;%20WOW64)%20AppleWebKit/537.36%20(KHTML,%20like

    $domain_name = 'http://www.' . $domain_name;
    $client = new Client(['headers' => ['User-Agent' => 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36']]);
    $response = $client->get($domain_name);

^导致“客户端错误:GET http://www.xxx.co.uk 导致‘403 Forbidden’”错误

    $domain_name = 'http://www.' . $domain_name;
    $client = new Client(['allow_redirects' => ['track_redirects' => true]]);
    $client->setServerParameter('user-agent', "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36");
    $response = $client->get($domain_name);

^导致“传递给 GuzzleHttp\Client::request() 的参数 3 必须是数组类型,给定的字符串”错误

    $domain_name = 'http://www.' . $domain_name;
    $client = new Client(['allow_redirects' => ['track_redirects' => true]]);
    $client->setHeader("user-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36");
    $response = $client->get($domain_name);

^ 还会导致“传递给 GuzzleHttp\Client::request() 的参数 3 必须是数组类型,给定的字符串”错误

有什么建议吗?我想我在这里掉进了一个兔子洞!

我想知道这里是否还有其他问题,因为据我了解,Guzzle 只是 CURL 的包装器,CURL 可以毫无问题地从同一个 IP 获取同一个网页。

似乎 user-agent 并不是唯一的 header 某些主机需要服务 HTML,我还必须添加 'accepts' header, 最后这解决了我与许多主机的问题:

$response = $client->request('GET', 'http://acme.com', [
  'headers' => [
    'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36',
    'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
  ]
]);