用 PHP 抓取 Instagram

Posted

技术标签:

【中文标题】用 PHP 抓取 Instagram【英文标题】:Instagram Scraping in PHP 【发布时间】:2016-10-04 23:14:39 【问题描述】:

我想在我的 Instagram 关注者项目中添加一个功能。

<?php
    function callInstagram($url)
    
        $ch = curl_init();
        curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 2));

        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    

    $url = "https://www.instagram.com/xyz/";
    $dom = new domDocument();  
    $dom->loadhtml($result); 
    $dom->preserveWhiteSpace = false; 
    $tables = $dom->getElementsByTagName('script type'); 
    ?>

我正在使用 DOM 从 HTML:'script type' 开始获取内容,但无法获取。

【问题讨论】:

【参考方案1】:

您实际上应该调用callInstagram($url) 函数,否则您的$result 变量将为空。因此,主程序应该像这样开始(添加第二行):

$url = "https://www.instagram.com/ravij28/";
$result = callInstagram($url);
$dom = new DOMDocument();  
$dom->loadHTML($result); 
[..]

另外,当您要检索页面上的脚本时,您需要使用标签名称,即script,而不是script type。因此,您的 sn-p 的最后一行需要阅读:

$tables = $dom->getElementsByTagName('script'); 

【讨论】:

我还需要卷曲部分吗?如果是,那么我应该在哪里定义 $result = callInstagram($url)? 是的,保留它。在创建 DOMDocument 实例之前,只需在主程序中添加一行,如我的代码 sn-p 所示。 $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 2)) $result = curl_exec($ch); curl_close($ch);返回$结果; $url = "instagram.com/ravij28/"; $result = callInstagram($url); $dom = 新的 domDocument(); $dom->loadHTML($result); $dom->preserveWhiteSpace = false; $tables = $dom->getElementsByTagName('script'); print_r($tables); ?> 仍然显示意外 $result 的错误【参考方案2】:

看看这个库:https://github.com/raiym/instagram-php-scraper

它允许您在没有身份验证的情况下抓取照片、视频、cmets。

使用这个库,您实际上可以抓取关注者甚至发布照片和视频: https://github.com/mgp25/Instagram-API

但它是私有 API

【讨论】:

【参考方案3】:

抓取 Instagram 很困难,尤其是从数据中心 IP 范围内 - 它只是一直抛出 302 重定向来登录。我尝试过https://github.com/raiym/instagram-php-scraper,这是一个很棒的库,然后为了解决访问问题,我不得不创建这个包的一个分支,它还可以处理引擎盖下的住宅代理,我可以推荐: https://github.com/restyler/instagram-php-scraper

这是一个带有简短教程的视频: https://www.youtube.com/watch?v=fHvjJ6IHQmw

【讨论】:

正在使用你的库,谢谢你的时间;我意识到它已经被删除了,你被停止了吗?

以上是关于用 PHP 抓取 Instagram的主要内容,如果未能解决你的问题,请参考以下文章

用PHP的curl实现并发请求远程文件(抓取远程网页)

如何用php 编写网络爬虫?

PHP cURL抓取网上图片

php分享十八:网页抓取

抓取远程图片到本地,你会用什么函数?

PHP 抓取 HTTPS 网站内容