为什么Instagram对CURL请求返回空白?

问题描述:

我写下面的代码来获取来自url的html数据,它的工作像https这样的Facebook网站,但不适用于Instagram。 Instagram的返回空白为什么Instagram对CURL请求返回空白?

<?php 
$url = 'https://www.instagram.com'; 
$returned_content = get_data($url); 
print_r($returned_content) 
/* gets the data from a URL */ 
function get_data($url) { 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 
?> 
+3

因为这里有一个语法错误。 –

+0

除了语法错误,您正在使用'print_r()'来打印输出。如果你使用'var_dump()',你会看到字符串的实际大小,但它仍然会显示为空字符串,因为该函数不分析HTML输出,所以它被你的浏览器解释。尝试使用'htmlspecialchars()'(尽管我不确定这是否是您想要实现的) – Brian

+1

您需要使用'htmlspecialchars($ returned_content)'在浏览器中查看不带渲染的响应。 'www.instagram.com'将返回'

'和'',但''只是javascript,不能由curl自己处理。 JS不能在你的浏览器中工作,因为你的域是不同的,所以不可能到达这个文件并且可能有一个CORS。 – Inkeliz

这里试试这

<?php 
$url = 'https://www.instagram.com'; 
$returned_content = get_data($url); 
print_r($returned_content); 
/* gets the data from a URL */ 
function get_data($url) { 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    //Update................. 
    curl_setopt($ch, CURLOPT_USERAGENT, 'spider'); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_HEADER, false); 
    //.................................................... 
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 
?> 

你应该通过如上 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false)信息。 欲了解更多详情请参阅 http://*.com/questions/4372710/php-curl-https

的Instagram的将只返回的javascript,不能用你的浏览器,因为它使用动态路径渲染,所以<script src='/path/file.js'>会想方设法把instagram.com/path/file.js在这种情况下localhost/path/file.js代替localhost/path/file.js不会存在,所以页面将是空白


一种解决方案是找到一种方法来给完整的HTML代替的Javascript的,在这种情况下,你可以使用“用户代理”做这一招。 你可能知道JS没有被搜索引擎处理,所以在这种情况下,Instagram(以及许多网站)会给出没有JS支持的页面。

因此,补充一点:

curl_setopt($ch, CURLOPT_USERAGENT, "ABACHOBot"); 

的 “ABACHOBot” 是爬行。 In this page you can found many others alternatives,就像是“Baiduspider”,“BecomeBot”......

你也可以使用“通用”用户代理,比如“bot”,“spider”,“crawler”,并且可能也会起作用。