Skip to content

Instantly share code, notes, and snippets.

@HimbeersaftLP
Last active January 14, 2020 21:03
Show Gist options
  • Save HimbeersaftLP/c68fed3df9e3bbce8b40c39277a3588f to your computer and use it in GitHub Desktop.
Save HimbeersaftLP/c68fed3df9e3bbce8b40c39277a3588f to your computer and use it in GitHub Desktop.
Instagram downloader, supports albums, images, videos and albums with images and videos.
import sys, os, json, re
import urllib.request as req
if (len(sys.argv) < 2):
print("Usage: instaload.py <url>")
sys.exit(1)
url = sys.argv[1]
url = re.sub(r"\?.*", "", url)
url = url + "?__a=1"
print("URL: " + url)
html = req.urlopen(url).read()
# jsonData = re.search(r"window\._sharedData = (.+);<\/script>", html).group(1)
# data = json.loads(jsonData)["entry_data"]["PostPage"][0]["graphql"]["shortcode_media"]
jsonData = html
data = json.loads(jsonData)["graphql"]["shortcode_media"]
shortcode = data["shortcode"]
def handleNode(node, index = -1):
if node["is_video"]:
print("Media is video")
dlFile(node["video_url"], "mp4", index)
else:
print("Media is image")
dlBestImage(node["display_resources"], index)
def dlFile(url, type, index = -1):
if index == -1:
fileName = shortcode + "." + type
else:
fileName = shortcode + "_" + str(index) + "." + type
print("Downloading: " + url)
os.system("curl -so \'" + fileName + "\' \'" + url + "\'")
def dlBestImage(display_resources, index = -1):
url = display_resources[-1]["src"]
dlFile(url, "jpg", index)
if "edge_sidecar_to_children" in data:
sys.stderr.write("Album detected\n")
nodes = data["edge_sidecar_to_children"]["edges"]
index = 0
for node in nodes:
handleNode(node["node"], index)
index += 1
else:
sys.stderr.write("Single media detected\n")
handleNode(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment