【问题标题】:file_get_contents/curl and 400 Bad Request for some urls (walmart..)file_get_contents/curl 和 400 Bad Request for some urls (walmart..)
【发布时间】:2016-05-30 18:41:45
【问题描述】:

在 php 中,我希望使用 file_get_contents 废弃一些 url。

对于大多数网址,它都有效,但对于某些网址,例如 walmart.com、buybuybaby.com。

源代码很简单,但是有一个技巧可以提取这些网址(walmart.com ...)??

我尝试使用 file_get_contents,也尝试使用 curl,但仍然无法正常工作

提前感谢您的帮助

$url="http://www.buybuybaby.com/";
$homepage = file_get_contents($url);
echo $homepage;

错误: 警告:file_get_contents(https://www.buybuybaby.com/):打开流失败:HTTP 请求失败! HTTP/1.0 400 错误请求

【问题讨论】:

  • 用于拒绝机器人请求的最常见(基本)“检查”是检查 User-Agent 标头是否与实际浏览器的标头匹配。 // 但如果这些网站已经采取了这种措施,那么他们可能不希望你首先抓取他们的内容。
  • @CBroe - 这不是这里发生的事情。服务器只是对请求感到窒息。
  • @CBroe:很容易测试。如果您将“我是机器人”作为用户代理发送,您将获得良好的响应。
  • 感谢您的回答!

标签: php curl web-scraping file-get-contents simple-html-dom


【解决方案1】:

你应该使用 curl 而不是

function curl_get_content($url, $post = "", $refer = "", $usecookie = false)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);

    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }

    if ($refer) {
        curl_setopt($curl, CURLOPT_REFERER, $refer);
    }

    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    //curl_setopt($curl, CURLOPT_TIMEOUT_MS, 5000);

    if ($usecookie) {
        curl_setopt($curl, CURLOPT_COOKIEJAR, $usecookie);
       curl_setopt($curl, CURLOPT_COOKIEFILE, $usecookie);
    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $html = curl_exec($curl);
    if (curl_error($curl)) {
       echo 'Loi CURL : ' . (curl_error($curl));
    }
    curl_close($curl);
    return $html;
}

因为file_get_contents函数发送请求不包括header信息或use-agent信息。 CURL 生成类似于浏览器请求的请求。还有 walmart、amazon、facebook 等……不要扣留你的要求

【讨论】:

  • 嗯,对于某些 URL,它的工作方式很奇怪。例如,我只有 URL official.my/freebacklinks.php 的特殊字符 ....任何想法?
猜你喜欢
  • 2011-09-13
  • 2012-01-18
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
相关资源
最近更新 更多