Skip to content

Instantly share code, notes, and snippets.

@rubinovitz
Created August 27, 2013 00:00
Show Gist options
  • Save rubinovitz/6348163 to your computer and use it in GitHub Desktop.
Save rubinovitz/6348163 to your computer and use it in GitHub Desktop.
A python script for downloading all of the instagram photos of a certain hashtag I wrote for a friend in 20 minutes (forgive sloppiness). Warning: you're only allowed 30 API requests an hour. Requires your own access token set as environment variable "access_token".
from datetime import datetime
import urllib2
import urllib
import json
import os
def ajaxRequest(url=None):
"""
Makes an ajax get request.
url - endpoint(string)
"""
req = urllib2.Request(url)
f = urllib2.urlopen(req)
response = f.read()
f.close()
return response
access_token = os.getenv("access_token")
# ask for hashtag name
hashtag = raw_input("What hashtag would you like to download photos of? ")
# url to query for pictures
nextUrl = "https://api.instagram.com/v1/tags/"+hashtag+"/media/recent?access_token="+access_token
print nextUrl
# while there is a next url to go to
while nextUrl:
# request the data at that endpoint
instagramJSON = ajaxRequest(nextUrl)
instagramDict = json.loads(instagramJSON)
# get new nextUrl
nextUrl = instagramDict["pagination"]["next_url"]
instagramData = instagramDict["data"]
# for every picture
for picDict in instagramData:
# get the image url and current time
print picDict
image = picDict["images"]["standard_resolution"]
imageUrl = image["url"]
print image
time = str(datetime.now())
# download the photo and save it
urllib.urlretrieve(imageUrl, time+".jpg")
@lkspa
Copy link

lkspa commented Oct 23, 2015

hi
i used your code but i had problems

i used for a hashtag with 2 photos, can u help me?

my problem is key error next url

@erajan96
Copy link

How Many Photos will it Retrieve for a Request?

@vinil2584
Copy link

Will this code work in Python 3.5? I see print method do not have parenthesis in your code, it seems it is Python 2 right

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