Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick-and-dirty Instagram web scrape, just in case you don't think you should have to make your users log in to deliver them public photos.
<?php
//returns a big old hunk of JSON from a non-private IG account page.
function scrape_insta($username) {
$insta_source = file_get_contents('http://instagram.com/'.$username);
$shards = explode('window._sharedData = ', $insta_source);
$insta_json = explode(';</script>', $shards[1]);
$insta_array = json_decode($insta_json[0], TRUE);
return $insta_array;
}
//Supply a username
$my_account = 'cosmocatalano';
//Do the deed
$results_array = scrape_insta($my_account);
//An example of where to go from there
$latest_array = $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][0];
echo 'Latest Photo:<br/>';
echo '<a href="http://instagram.com/p/'.$latest_array['code'].'"><img src="'.$latest_array['display_src'].'"></a></br>';
echo 'Likes: '.$latest_array['likes']['count'].' - Comments: '.$latest_array['comments']['count'].'<br/>';
/* BAH! An Instagram site redesign in June 2015 broke quick retrieval of captions, locations and some other stuff.
echo 'Taken at '.$latest_array['location']['name'].'<br/>';
//Heck, lets compare it to a useful API, just for kicks.
echo '<img src="http://maps.googleapis.com/maps/api/staticmap?markers=color:red%7Clabel:X%7C'.$latest_array['location']['latitude'].','.$latest_array['location']['longitude'].'&zoom=13&size=300x150&sensor=false">';
?>
*/
@Vheissu

This comment has been minimized.

Show comment
Hide comment
@Vheissu

Vheissu Feb 17, 2014

Amazingly simple and effective. Thank you for sharing this.

Vheissu commented Feb 17, 2014

Amazingly simple and effective. Thank you for sharing this.

@tomtheman2

This comment has been minimized.

Show comment
Hide comment
@tomtheman2

tomtheman2 Aug 27, 2014

Hi,
How can one go about running this script?
Thanks

tomtheman2 commented Aug 27, 2014

Hi,
How can one go about running this script?
Thanks

@slang800

This comment has been minimized.

Show comment
Hide comment
@slang800

slang800 Apr 16, 2015

made a similar tool over here, to get a user's entire history: https://github.com/slang800/instagram-screen-scrape

slang800 commented Apr 16, 2015

made a similar tool over here, to get a user's entire history: https://github.com/slang800/instagram-screen-scrape

@aboustayyef

This comment has been minimized.

Show comment
Hide comment
@aboustayyef

aboustayyef Apr 18, 2015

Here's a quick class to only get the image from an Instagram image url:

<?php 

class InstagramScraper
{
    protected $content;
    function __construct($url)
    {
        $this->content = @file_get_contents($url);
    }

    public function image(){
        preg_match('#<meta +property=\\"og:image\\" +content=\\"(http.+?\.jpg)\\"#', $this->content, $result);
        return $result[1];
    }
}
?>

aboustayyef commented Apr 18, 2015

Here's a quick class to only get the image from an Instagram image url:

<?php 

class InstagramScraper
{
    protected $content;
    function __construct($url)
    {
        $this->content = @file_get_contents($url);
    }

    public function image(){
        preg_match('#<meta +property=\\"og:image\\" +content=\\"(http.+?\.jpg)\\"#', $this->content, $result);
        return $result[1];
    }
}
?>
@mscreenie

This comment has been minimized.

Show comment
Hide comment
@mscreenie

mscreenie Jul 24, 2015

Still working given the recent changes to Instagram?

mscreenie commented Jul 24, 2015

Still working given the recent changes to Instagram?

@dreszczyk

This comment has been minimized.

Show comment
Hide comment

dreszczyk commented Nov 27, 2015

@Nimoi

This comment has been minimized.

Show comment
Hide comment
@Nimoi

Nimoi Dec 8, 2015

Thanks! I needed to scrape some individual posts. This still works.

Nimoi commented Dec 8, 2015

Thanks! I needed to scrape some individual posts. This still works.

@lmj0011

This comment has been minimized.

Show comment
Hide comment
@lmj0011

lmj0011 Dec 16, 2015

if you want to get back a certain number of images, just increment the $results_array like so:

 for($cnt=0; $cnt < 20; $cnt++)
{
 $latest_array = $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][$cnt];

 echo 'Latest Photo:<br/>';
 echo '<a href="http://instagram.com/p/'.$latest_array['code'].'"><img src="'.$latest_array['display_src'].'"></a></br>';
 echo 'Likes: '.$latest_array['likes']['count'].' - Comments: '.$latest_array['comments']['count'].'<br/>';
}

lmj0011 commented Dec 16, 2015

if you want to get back a certain number of images, just increment the $results_array like so:

 for($cnt=0; $cnt < 20; $cnt++)
{
 $latest_array = $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][$cnt];

 echo 'Latest Photo:<br/>';
 echo '<a href="http://instagram.com/p/'.$latest_array['code'].'"><img src="'.$latest_array['display_src'].'"></a></br>';
 echo 'Likes: '.$latest_array['likes']['count'].' - Comments: '.$latest_array['comments']['count'].'<br/>';
}
@AdelDima

This comment has been minimized.

Show comment
Hide comment
@AdelDima

AdelDima Feb 28, 2016

Thanks for sharing this gist

AdelDima commented Feb 28, 2016

Thanks for sharing this gist

@JacksonPoultney

This comment has been minimized.

Show comment
Hide comment
@JacksonPoultney

JacksonPoultney Mar 13, 2016

Thank you so much for this, love the quick and dirty-ness of it! I have a couple of questions if you can help.

  • How can I set the number of posts to display? I'd like to show 2 or 4 of the latest
  • Is it possible to get the images by location ID using a slightly modified method? That's what I was initially trying to do, if it's not possible the userID works ok as well.

Thanks again.

JacksonPoultney commented Mar 13, 2016

Thank you so much for this, love the quick and dirty-ness of it! I have a couple of questions if you can help.

  • How can I set the number of posts to display? I'd like to show 2 or 4 of the latest
  • Is it possible to get the images by location ID using a slightly modified method? That's what I was initially trying to do, if it's not possible the userID works ok as well.

Thanks again.

@raiym

This comment has been minimized.

Show comment
Hide comment

raiym commented Apr 22, 2016

@ravij28

This comment has been minimized.

Show comment
Hide comment
@ravij28

ravij28 Jun 2, 2016

It's showing below error:

Warning: file_get_contents(http://instagram.com/ascia_akf): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in C:\wamp\www\Trial\curl.php on line 4

Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\Trial\curl.php on line 4

ravij28 commented Jun 2, 2016

It's showing below error:

Warning: file_get_contents(http://instagram.com/ascia_akf): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in C:\wamp\www\Trial\curl.php on line 4

Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\Trial\curl.php on line 4

@pistell

This comment has been minimized.

Show comment
Hide comment
@pistell

pistell Jun 2, 2016

@cosmocatalano I seriously owe you a beer or twelve for this. The Instagram API migration ruined my app and this saved me.

pistell commented Jun 2, 2016

@cosmocatalano I seriously owe you a beer or twelve for this. The Instagram API migration ruined my app and this saved me.

@socca1157

This comment has been minimized.

Show comment
Hide comment
@socca1157

socca1157 Jun 4, 2016

Awesome script, anyway to get more than 15 photos though? Or get the ajax from the load more button?

socca1157 commented Jun 4, 2016

Awesome script, anyway to get more than 15 photos though? Or get the ajax from the load more button?

@ashish21590

This comment has been minimized.

Show comment
Hide comment
@ashish21590

ashish21590 Jun 4, 2016

Script works fine but can you please guide me to get more then 15 posts ?

ashish21590 commented Jun 4, 2016

Script works fine but can you please guide me to get more then 15 posts ?

@hardiksondagar

This comment has been minimized.

Show comment
Hide comment
@hardiksondagar

hardiksondagar Jun 30, 2016

I've made web scrapper to get user X's followers using javascript that stores followers and exports in csv files. All you need to do is to keep scrolling.

/**
 * 
 * Instagram Follower Web Scrapper 
 * 
 * Steps to use.
 * 1. Open instagram user's profile in browser https://www.instagram.com/tvfpitchers/
 * 2. Open console ( press F12 in chrome ) and paste all the code below
 * 3. Click on followers button and load all the followers
 * 4. Call function downloadAsCsv() by writing "downloadAsCsv()" in console to download csv file containing user's all the followers .
 * 
 * @author : Hardik Sondagar <hardikmsondagar@gmail.com>
 * 
 */

var followers = [];

(function(XHR) {
    "use strict";

    var stats = [];
    var timeoutId = null;

    var open = XHR.prototype.open;
    var send = XHR.prototype.send;

    XHR.prototype.open = function(method, url, async, user, pass) {
        this._url = url;
        open.call(this, method, url, async, user, pass);
    };

    XHR.prototype.send = function(data) {
        var self = this;
        var start;
        var oldOnReadyStateChange;
        var url = this._url;

        function onReadyStateChange() {
            if(self.readyState == 4 && url == 'https://www.instagram.com/query/') {

              var response = JSON.parse(self.response);
              followers = followers.concat(response.followed_by.nodes);

            }

            if(oldOnReadyStateChange) {
                oldOnReadyStateChange();
            }
        }

        if(!this.noIntercept) {
            start = new Date();

            if(this.addEventListener) {
                this.addEventListener("readystatechange", onReadyStateChange, false);
            } else {
                oldOnReadyStateChange = this.onreadystatechange; 
                this.onreadystatechange = onReadyStateChange;
            }
        }

        send.call(this, data);
    }
})(XMLHttpRequest);

function downloadAsCsv() {



    var csvContent = "data:text/csv;charset=utf-8,";

    var header = "Username,Requested_by_viewer,Followed_by_viewer,Profile_pic_url,Full Name,is_verified,Id\n";
    csvContent += header;

    followers.forEach(function(infoArray, index){

        var data = $.map(infoArray, function(value) {
        return [value];
        });

        dataString = data.join(",");
        csvContent += index < followers.length ? dataString+ "\n" : dataString;

    });

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);

    var pathArray = window.location.pathname.split('/');

    var milliseconds = (new Date).getTime();
    var filename = 'followers.'+ milliseconds +'.csv';

    if(pathArray && pathArray.length > 1) {
        filename = pathArray[1] + '.' + milliseconds +'.csv';
    }
    link.setAttribute("download",filename);
    document.body.appendChild(link); // Required for FF

    link.click(); // This will download the data file named "my_data.csv".

}

hardiksondagar commented Jun 30, 2016

I've made web scrapper to get user X's followers using javascript that stores followers and exports in csv files. All you need to do is to keep scrolling.

/**
 * 
 * Instagram Follower Web Scrapper 
 * 
 * Steps to use.
 * 1. Open instagram user's profile in browser https://www.instagram.com/tvfpitchers/
 * 2. Open console ( press F12 in chrome ) and paste all the code below
 * 3. Click on followers button and load all the followers
 * 4. Call function downloadAsCsv() by writing "downloadAsCsv()" in console to download csv file containing user's all the followers .
 * 
 * @author : Hardik Sondagar <hardikmsondagar@gmail.com>
 * 
 */

var followers = [];

(function(XHR) {
    "use strict";

    var stats = [];
    var timeoutId = null;

    var open = XHR.prototype.open;
    var send = XHR.prototype.send;

    XHR.prototype.open = function(method, url, async, user, pass) {
        this._url = url;
        open.call(this, method, url, async, user, pass);
    };

    XHR.prototype.send = function(data) {
        var self = this;
        var start;
        var oldOnReadyStateChange;
        var url = this._url;

        function onReadyStateChange() {
            if(self.readyState == 4 && url == 'https://www.instagram.com/query/') {

              var response = JSON.parse(self.response);
              followers = followers.concat(response.followed_by.nodes);

            }

            if(oldOnReadyStateChange) {
                oldOnReadyStateChange();
            }
        }

        if(!this.noIntercept) {
            start = new Date();

            if(this.addEventListener) {
                this.addEventListener("readystatechange", onReadyStateChange, false);
            } else {
                oldOnReadyStateChange = this.onreadystatechange; 
                this.onreadystatechange = onReadyStateChange;
            }
        }

        send.call(this, data);
    }
})(XMLHttpRequest);

function downloadAsCsv() {



    var csvContent = "data:text/csv;charset=utf-8,";

    var header = "Username,Requested_by_viewer,Followed_by_viewer,Profile_pic_url,Full Name,is_verified,Id\n";
    csvContent += header;

    followers.forEach(function(infoArray, index){

        var data = $.map(infoArray, function(value) {
        return [value];
        });

        dataString = data.join(",");
        csvContent += index < followers.length ? dataString+ "\n" : dataString;

    });

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);

    var pathArray = window.location.pathname.split('/');

    var milliseconds = (new Date).getTime();
    var filename = 'followers.'+ milliseconds +'.csv';

    if(pathArray && pathArray.length > 1) {
        filename = pathArray[1] + '.' + milliseconds +'.csv';
    }
    link.setAttribute("download",filename);
    document.body.appendChild(link); // Required for FF

    link.click(); // This will download the data file named "my_data.csv".

}
@sripadks

This comment has been minimized.

Show comment
Hide comment
@sripadks

sripadks Jul 1, 2016

@hardiksondagar when I try to use your script, chrome just says "undefined" when I both enter the code into the console as well as run the function. The downloaded CSV is empty.

sripadks commented Jul 1, 2016

@hardiksondagar when I try to use your script, chrome just says "undefined" when I both enter the code into the console as well as run the function. The downloaded CSV is empty.

@techinpark

This comment has been minimized.

Show comment
Hide comment
@techinpark

techinpark commented Jul 8, 2016

@hardiksondagar same result.

@pipep

This comment has been minimized.

Show comment
Hide comment
@pipep

pipep Sep 20, 2016

Sorry for my ignorance, i'm starting with this.. how could I get more than 1 username to be processed on one page ? I get an error all the time.. I need ig-A + ig-B + ig-C latest pictures on one page.. any ideas ?

Thank you !

pipep commented Sep 20, 2016

Sorry for my ignorance, i'm starting with this.. how could I get more than 1 username to be processed on one page ? I get an error all the time.. I need ig-A + ig-B + ig-C latest pictures on one page.. any ideas ?

Thank you !

@AlchemyUnited

This comment has been minimized.

Show comment
Hide comment
@AlchemyUnited

AlchemyUnited Oct 21, 2016

Does anyone know if this is still working? My get_file_contents() is returning the Instagram signup page. Have then since done some sort of scrape prevention?

AlchemyUnited commented Oct 21, 2016

Does anyone know if this is still working? My get_file_contents() is returning the Instagram signup page. Have then since done some sort of scrape prevention?

@nivalexstan

This comment has been minimized.

Show comment
Hide comment
@nivalexstan

nivalexstan Oct 24, 2016

How to scrape register emails with Instagram accounts ?

nivalexstan commented Oct 24, 2016

How to scrape register emails with Instagram accounts ?

@cryptologica

This comment has been minimized.

Show comment
Hide comment
@cryptologica

cryptologica Mar 6, 2017

Thanks, this worked great! I modified it to get the 12 most recent photos:

<?php
//returns a big old hunk of JSON from a non-private IG account page.
function scrape_insta($username) {
	$insta_source = file_get_contents('http://instagram.com/'.$username);
	$shards = explode('window._sharedData = ', $insta_source);
	$insta_json = explode(';</script>', $shards[1]);
	$insta_array = json_decode($insta_json[0], TRUE);
	return $insta_array;
}
//Supply a username
$my_account = 'my_instagram_username';
$results_array = scrape_insta($my_account);

// Create a comma-separated list of the first 12 image source URLs.
$url_list = $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][0]['display_src'];
for ($i=1; $i < 12; $i++) {
	$url_list .= ',' . $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][$i]['display_src'];
}

// Print out the list. Use Ajax.get() or something to call this script, then parse it on client: list.split(',').
echo $url_list;
?>

cryptologica commented Mar 6, 2017

Thanks, this worked great! I modified it to get the 12 most recent photos:

<?php
//returns a big old hunk of JSON from a non-private IG account page.
function scrape_insta($username) {
	$insta_source = file_get_contents('http://instagram.com/'.$username);
	$shards = explode('window._sharedData = ', $insta_source);
	$insta_json = explode(';</script>', $shards[1]);
	$insta_array = json_decode($insta_json[0], TRUE);
	return $insta_array;
}
//Supply a username
$my_account = 'my_instagram_username';
$results_array = scrape_insta($my_account);

// Create a comma-separated list of the first 12 image source URLs.
$url_list = $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][0]['display_src'];
for ($i=1; $i < 12; $i++) {
	$url_list .= ',' . $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][$i]['display_src'];
}

// Print out the list. Use Ajax.get() or something to call this script, then parse it on client: list.split(',').
echo $url_list;
?>
@BHFR

This comment has been minimized.

Show comment
Hide comment
@BHFR

BHFR Mar 11, 2017

Thanks for sharing bro !

BHFR commented Mar 11, 2017

Thanks for sharing bro !

@adi64bit

This comment has been minimized.

Show comment
Hide comment
@adi64bit

adi64bit Mar 16, 2017

just add "?__a=1" at the end of url, it's already JSON
ex:
"http://instagram.com/username/?__a=1" for username
"http://instagram.com/tags/hashtag/?__a=1" for hashtag

adi64bit commented Mar 16, 2017

just add "?__a=1" at the end of url, it's already JSON
ex:
"http://instagram.com/username/?__a=1" for username
"http://instagram.com/tags/hashtag/?__a=1" for hashtag

@JulienBlancher

This comment has been minimized.

Show comment
Hide comment

JulienBlancher commented Mar 29, 2017

Thanks @adi64bit!!

@Spandan-Madan

This comment has been minimized.

Show comment
Hide comment
@Spandan-Madan

Spandan-Madan Apr 3, 2017

Is this still working? Planning to use it for a research project!

Spandan-Madan commented Apr 3, 2017

Is this still working? Planning to use it for a research project!

@edogaafx

This comment has been minimized.

Show comment
Hide comment
@edogaafx

edogaafx Apr 10, 2017

Thank You for sharing code! Helped a lot with possibility to avoid API.
@adi64bit thanks, that made things way more easier! Maybe you could share link, where can get more this kind of useful links?

edogaafx commented Apr 10, 2017

Thank You for sharing code! Helped a lot with possibility to avoid API.
@adi64bit thanks, that made things way more easier! Maybe you could share link, where can get more this kind of useful links?

@grohsfabian

This comment has been minimized.

Show comment
Hide comment
@grohsfabian

grohsfabian May 7, 2017

If any of you guys need an instagram nodejs bot, check out my profile repo :)

grohsfabian commented May 7, 2017

If any of you guys need an instagram nodejs bot, check out my profile repo :)

@transbetacism

This comment has been minimized.

Show comment
Hide comment
@transbetacism

transbetacism May 25, 2017

TIP: If you want square images (1x1 ratio), replace ['display_src'] with ['thumbnail_src'].

transbetacism commented May 25, 2017

TIP: If you want square images (1x1 ratio), replace ['display_src'] with ['thumbnail_src'].

@DoublingtheLift

This comment has been minimized.

Show comment
Hide comment
@DoublingtheLift

DoublingtheLift Jun 2, 2017

Does anyone know what you add to the script to grab the captions from all post in the account. when I added @lmj0011 edits it just gave me the same post over and over again instead of jumping to the next post.

DoublingtheLift commented Jun 2, 2017

Does anyone know what you add to the script to grab the captions from all post in the account. when I added @lmj0011 edits it just gave me the same post over and over again instead of jumping to the next post.

@jakim

This comment has been minimized.

Show comment
Hide comment
@jakim

jakim Jun 5, 2017

Nice find @adi64bit, thanks!

jakim commented Jun 5, 2017

Nice find @adi64bit, thanks!

@aehacker

This comment has been minimized.

Show comment
Hide comment
@aehacker

aehacker Jul 6, 2017

**can we get all image from instagram account ? (detect html code and get image urls ? )

Help me to create it!!**

aehacker commented Jul 6, 2017

**can we get all image from instagram account ? (detect html code and get image urls ? )

Help me to create it!!**

@vivekkmsh

This comment has been minimized.

Show comment
Hide comment
@vivekkmsh

vivekkmsh Oct 13, 2017

I am scraping hashtag data but its showing me only limited number of records, Please advise me how to scrap all data.

vivekkmsh commented Oct 13, 2017

I am scraping hashtag data but its showing me only limited number of records, Please advise me how to scrap all data.

@Voskuijlen

This comment has been minimized.

Show comment
Hide comment
@Voskuijlen

Voskuijlen Nov 16, 2017

If you are scraping a hashtag or username with @adi64bit his method, it will return a media attribute with some properties.
This media attribute contains the nodes that you are probably using to display the images. There also is a property called "page_info". This property contains information about the obtained nodes like if more nodes exists and the cursor to obtain those next nodes.

"media": { "count": 23, "nodes": [ ... ], "page_info": { "has_next_page": true, "end_cursor": "some_identifier" } }

Note: There also is an attribute called "count", this is the total amount of nodes.

After obtaining that end_cursor you might be able to obtain the next few nodes. Adding an additional parameter to the URL given by @adi64bit called "max_id" will give you the next few nodes like so:

"http://instagram.com/username/?__a=1&max_id=some_identifier" for username
"http://instagram.com/tags/hashtag/?__a=1&max_id=some_identifier" for hashtag

Voskuijlen commented Nov 16, 2017

If you are scraping a hashtag or username with @adi64bit his method, it will return a media attribute with some properties.
This media attribute contains the nodes that you are probably using to display the images. There also is a property called "page_info". This property contains information about the obtained nodes like if more nodes exists and the cursor to obtain those next nodes.

"media": { "count": 23, "nodes": [ ... ], "page_info": { "has_next_page": true, "end_cursor": "some_identifier" } }

Note: There also is an attribute called "count", this is the total amount of nodes.

After obtaining that end_cursor you might be able to obtain the next few nodes. Adding an additional parameter to the URL given by @adi64bit called "max_id" will give you the next few nodes like so:

"http://instagram.com/username/?__a=1&max_id=some_identifier" for username
"http://instagram.com/tags/hashtag/?__a=1&max_id=some_identifier" for hashtag

@sumanyu-soniwal

This comment has been minimized.

Show comment
Hide comment
@sumanyu-soniwal

sumanyu-soniwal Nov 19, 2017

Thanks a ton @Voskuijlen & @adi64bit
Any info on how can we get the username for a post and the time?

Like I'm using "http://instagram.com/tags/hashtag/?__a=1&max_id=some_identifier" for hashtag
I'm getting owner id in the results. Any way to fetch username from owner id?

sumanyu-soniwal commented Nov 19, 2017

Thanks a ton @Voskuijlen & @adi64bit
Any info on how can we get the username for a post and the time?

Like I'm using "http://instagram.com/tags/hashtag/?__a=1&max_id=some_identifier" for hashtag
I'm getting owner id in the results. Any way to fetch username from owner id?

@marciandmnd

This comment has been minimized.

Show comment
Hide comment
@marciandmnd

marciandmnd Nov 30, 2017

Excellent. Thanks!

marciandmnd commented Nov 30, 2017

Excellent. Thanks!

@ougrocks

This comment has been minimized.

Show comment
Hide comment
@ougrocks

ougrocks Dec 21, 2017

@sumanyu-soniwal yes if you want a username for a post and a time, it's simple, just give a get call to
https://api.instagram.com/oembed/?callback=&url=https://www.instagram.com/p/BcnNh0fB6Pc/

Replace URL parameter value with your post URL. It will provide you brief info regarding that post. [Mandatory - post should be public]
So by this simple method, you can fulfill your basic need as you mentioned regarding "username for a post and a time"

ougrocks commented Dec 21, 2017

@sumanyu-soniwal yes if you want a username for a post and a time, it's simple, just give a get call to
https://api.instagram.com/oembed/?callback=&url=https://www.instagram.com/p/BcnNh0fB6Pc/

Replace URL parameter value with your post URL. It will provide you brief info regarding that post. [Mandatory - post should be public]
So by this simple method, you can fulfill your basic need as you mentioned regarding "username for a post and a time"

@johnperricruz

This comment has been minimized.

Show comment
Hide comment
@johnperricruz

johnperricruz Jan 24, 2018

As of today, ?__a=1 for instagram does not work anymore.

Update : Working as of now.

johnperricruz commented Jan 24, 2018

As of today, ?__a=1 for instagram does not work anymore.

Update : Working as of now.

@alexandernacho

This comment has been minimized.

Show comment
Hide comment
@alexandernacho

alexandernacho Mar 2, 2018

Is there a way to scrape the mentions of a specific IG account, posted by other accounts? If hashtags can be collected, it should also work for comments on public posts, right?

alexandernacho commented Mar 2, 2018

Is there a way to scrape the mentions of a specific IG account, posted by other accounts? If hashtags can be collected, it should also work for comments on public posts, right?

@halimjr

This comment has been minimized.

Show comment
Hide comment
@halimjr

halimjr Mar 10, 2018

Is there any way to show top 10 liked post?

halimjr commented Mar 10, 2018

Is there any way to show top 10 liked post?

@halimjr

This comment has been minimized.

Show comment
Hide comment
@halimjr

halimjr Mar 10, 2018

This code only returns 12 recent posts, is there any way to get all the post?

halimjr commented Mar 10, 2018

This code only returns 12 recent posts, is there any way to get all the post?

@wpexplorer

This comment has been minimized.

Show comment
Hide comment
@wpexplorer

wpexplorer Mar 18, 2018

@halimjr - it can only return the number of items available by default on Instagram on initial load since it scrapes the loaded page.

wpexplorer commented Mar 18, 2018

@halimjr - it can only return the number of items available by default on Instagram on initial load since it scrapes the loaded page.

@NRandall

This comment has been minimized.

Show comment
Hide comment
@NRandall

NRandall Mar 21, 2018

Modified this to work with js client side - https://github.com/NRandall/igjs

NRandall commented Mar 21, 2018

Modified this to work with js client side - https://github.com/NRandall/igjs

@garudacrafts

This comment has been minimized.

Show comment
Hide comment
@garudacrafts

garudacrafts Mar 22, 2018

Instagram has updated their js and this script needs to be updated.

Starting at Line 19:
$latest_array = $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][0];

Should now be:
$latest_images = $results_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'];

And one can iterate over them like so:

$instagram_latest = array();

foreach ( $latest_images as $image_data ) {
		$image = $image_data['node'];

		$instagram_latest[] = array(
                    'description' => $image['edge_media_to_caption']['edges'][0]['node']['text'],
                    'link'        => '//instagram.com/p/' . $image['shortcode'],
                    'time'        => $image['taken_at_timestamp'],
                    'comments'    => $this->shorten_number($image['edge_media_to_comment']['count']),
                    'likes'       => $this->shorten_number($image['edge_media_preview_like']['count']) : '',
                    'thumbnail'   => $image['thumbnail_src'],
                    'media_preview' => $image['media_preview']
                );
}

garudacrafts commented Mar 22, 2018

Instagram has updated their js and this script needs to be updated.

Starting at Line 19:
$latest_array = $results_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'][0];

Should now be:
$latest_images = $results_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'];

And one can iterate over them like so:

$instagram_latest = array();

foreach ( $latest_images as $image_data ) {
		$image = $image_data['node'];

		$instagram_latest[] = array(
                    'description' => $image['edge_media_to_caption']['edges'][0]['node']['text'],
                    'link'        => '//instagram.com/p/' . $image['shortcode'],
                    'time'        => $image['taken_at_timestamp'],
                    'comments'    => $this->shorten_number($image['edge_media_to_comment']['count']),
                    'likes'       => $this->shorten_number($image['edge_media_preview_like']['count']) : '',
                    'thumbnail'   => $image['thumbnail_src'],
                    'media_preview' => $image['media_preview']
                );
}
@tayeke

This comment has been minimized.

Show comment
Hide comment
@tayeke

tayeke Apr 12, 2018

Thanks so much @garudacrafts for the update!

tayeke commented Apr 12, 2018

Thanks so much @garudacrafts for the update!

@bateller

This comment has been minimized.

Show comment
Hide comment
@bateller

bateller Apr 16, 2018

Thanks for the update @garudacrafts.

I was getting http://instagram.com/[username]/?__a=1 which returned a raw JSON array, however it looks like Instagram started blocking that in the last few days (presenting a 403 error now).

So instead I'm using this process which parses the raw HTML and parses out the javascript window._sharedData JSON array.

bateller commented Apr 16, 2018

Thanks for the update @garudacrafts.

I was getting http://instagram.com/[username]/?__a=1 which returned a raw JSON array, however it looks like Instagram started blocking that in the last few days (presenting a 403 error now).

So instead I'm using this process which parses the raw HTML and parses out the javascript window._sharedData JSON array.

@MaximKhrenov

This comment has been minimized.

Show comment
Hide comment
@MaximKhrenov

MaximKhrenov Apr 16, 2018

@garudacrafts How to split the output of 8 parts?

MaximKhrenov commented Apr 16, 2018

@garudacrafts How to split the output of 8 parts?

@kovalevandrew

This comment has been minimized.

Show comment
Hide comment
@kovalevandrew

kovalevandrew Apr 19, 2018

$username = 'username';
$insta_source = file_get_contents('http://instagram.com/'.$username);
$shards = explode('window._sharedData = ', $insta_source);
$insta_json = explode(';</script>', $shards[1]);
$results_array = json_decode($insta_json[0], TRUE);
for ($i=1; $i < 5; $i++) {
     $url_list[] =  $results_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'][$i]['node']['display_url'];
}

this is valid code on php to get images from account, enjoy guys :)

kovalevandrew commented Apr 19, 2018

$username = 'username';
$insta_source = file_get_contents('http://instagram.com/'.$username);
$shards = explode('window._sharedData = ', $insta_source);
$insta_json = explode(';</script>', $shards[1]);
$results_array = json_decode($insta_json[0], TRUE);
for ($i=1; $i < 5; $i++) {
     $url_list[] =  $results_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'][$i]['node']['display_url'];
}

this is valid code on php to get images from account, enjoy guys :)

@shoaibalich

This comment has been minimized.

Show comment
Hide comment
@shoaibalich

shoaibalich Apr 21, 2018

Noob question - is this illegal? I'd really like to apply this script since IG stop accepting API access for new developer apps.

shoaibalich commented Apr 21, 2018

Noob question - is this illegal? I'd really like to apply this script since IG stop accepting API access for new developer apps.

@Underdog89

This comment has been minimized.

Show comment
Hide comment
@Underdog89

Underdog89 Jun 21, 2018

@shoaibalich I suppose it depends how you are going to be using the data and storing it(if you are). I am using it for example just to display the number of followers an Instagram page has. This information is freely available on the internet anyway. It's no different to manually loading the page and making a note of the information.

Storing the information may be different though.

Underdog89 commented Jun 21, 2018

@shoaibalich I suppose it depends how you are going to be using the data and storing it(if you are). I am using it for example just to display the number of followers an Instagram page has. This information is freely available on the internet anyway. It's no different to manually loading the page and making a note of the information.

Storing the information may be different though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment