PHP不允许我输出某些网站的html,为什么?

时间:2016-07-15 14:17:18

标签: php web-scraping

我正在尝试构建一个基本的Web scraper。它适用于几乎任何网站,但有些网站我无法报废,为什么会这样?这是我的网站上的代码(本网站):

<!doctype html>
<html lang="en-US">
  <body>
    <?php
      $url ='http://stackoverflow.com/';
      $output = file_get_contents($url);
      echo $output;
    ?>
  </body>
</html>

在我自己的本地主机上运行时,会将stackoverflow.com的内容输出到我的站点。这是一个不适合的网站:

<!doctype html>
<html lang="en-US">
  <body>
    <?php
      $url ='https://www.galottery.com/en-us/home.html';
      $output = file_get_contents($url);
      echo $output;
    ?>
  </body>
</html>

我没有加载网站,而是收到了这个错误:

  

警告:file_get_contents(https://www.galottery.com/en-us/home.html):无法打开流:HTTP请求失败! HTTP / 1.1 403禁止在第6行的C:\ xampp \ htdocs \ projects \ QD \ webScraping \ index.php中

为什么这适用于某些网站而不适用于其他网站?我认为这可能是因为一个是HTTPS站点,但我已经尝试过这个代码,例如https://google.com,其工作正常。

我正在使用XAMMP来运行本地PHP。

2 个答案:

答案 0 :(得分:2)

要么他们正在检查UserAgent,要么他们禁止你的IP地址。

要模拟正确的UserAgent,您必须使用curl,如下所示:

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);

curl_setopt($ch, CURLOPT_URL, "https://www.galottery.com/en-us/home.html");
$result = curl_exec($ch);

echo $result;

虽然,他们可能会使用一些javascript重定向,比如。首先加载网页,他们正在设置cookie并执行document.location.href重定向。而不是检查那个cookie。

更新:刚刚测试过,我的解决方案运行正常。

答案 1 :(得分:2)

它的工作;

<?php

$ops =  array(
    'http' => array(
        'method' => "GET",
        'header' => "Accept-language: en\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n" .
                    "Cookie: foo=bar\r\n" . 
                    "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n"
    )
);

$context = stream_context_create($ops);

echo file_get_contents('https://www.galottery.com/en-us/home.html', false, $context);
相关问题