Instagram内容对file_get_contents()的响应时间非常长(超过10秒)

时间:2019-06-01 20:37:18

标签: php instagram file-get-contents php-7.1

我正在对某人的代码进行故障排除,该代码旨在从Instagram动态获取图片,然后将其打印在页面上。

问题是,流程本身基本上是整个页面的瓶颈,导致加载时间增加了10-12秒。

我似乎找不到导致此问题的特别原因。以前的谷歌搜索使我收到有关使用file_get_contents()时连接不会自动关闭的响应,但是从5.6版开始,尤其是从7.1版开始,这应该不是问题吗?

这是有问题的代码:

<?php

function scrape_insta_hash($tag) {
  $insta_source = file_get_contents('https://www.instagram.com/explore/tags/'.$tag.'/');
  $shards = explode('window._sharedData = ', $insta_source);
  $insta_json = explode(';</script>', $shards[1]);
  $insta_array = json_decode($insta_json[0], TRUE);
  return $insta_array;
}

$tag = "placeholder";
$results_array = scrape_insta_hash($tag);

$limit = 5;
$imgs = array();

for ($i=$limit; $i >= 0; $i--) {                  
  if(array_key_exists($i,$results_array['entry_data']['TagPage'][0]["graphql"]["hashtag"]["edge_hashtag_to_media"]["edges"])) {
    $latest_array = $results_array['entry_data']['TagPage'][0]["graphql"]["hashtag"]["edge_hashtag_to_media"]["edges"][$i]["node"];
    $newPosting = ["image"=>$latest_array['display_url']];
    $imgs[] = $newPosting['image'];
  }
}
?>

2 个答案:

答案 0 :(得分:0)

好吧,您在评论中证实了我的怀疑,所以我会这样做:

首先,我将调整剪贴方法以模仿浏览器请求。尝试使用标题,并在必要时添加更多内容。

<?php

function scrape_insta_hash($tag) {
  $opts = [
     "http" => [
        "method" => "GET",
        "header" => "Accept-language: en\r\n" .
            "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.109\r\n"
         ]
  ];

  $context = stream_context_create($opts);

  $insta_source = file_get_contents('https://www.instagram.com/explore/tags/'.$tag.'/', false, $context);
  file_get_contents('https://www.instagram.com/explore/tags/'.$tag.'/');
  $shards = explode('window._sharedData = ', $insta_source);
  $insta_json = explode(';</script>', $shards[1]);
  $insta_array = json_decode($insta_json[0], TRUE);
  return $insta_array;
}

因为您获取页面的方式是Instagram会将您注册为php机器人。

然后在您在循环中发出请求的代码部分中添加一个小的超时时间:

foreach($tags as $tag) {
    $res = scrape_insta_hash($tag);
    ...

    // Sleep for half a second
    usleep(500000);
}

还可以尝试使用睡眠编号,以了解可以输入的最低值。我的意思是这里没有确切的答案,您需要进行很多反复试验才能解决Instagram的限制机制。

另外有用的是使用不同的IP地址,也许一旦受到限制,就可以使用一些VPN作为代理并更改IP地址。

正如您提到的,缓存机制也不是一个坏主意,但是您需要一种方法来确定页面是否发生了更改,因为乍一看,我看不到任何有用的标题,根据Instagram的响应标头,此页面从不缓存,没有etags,您可真正用作检查。

答案 1 :(得分:0)

更新到PHP 7后,我遇到了同样的问题。 file_get_contents()在PHP 5中速度惊人,但在PHP 7中却很烂。我通过使用 curl()< / strong>。您也应该尝试。