Last active
December 8, 2017 14:56
-
-
Save mnordin/351b4b172233249f914bffdc7602f3de to your computer and use it in GitHub Desktop.
Download all images from a public Instagram account or hashtag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'cgi' | |
| require 'open-uri' | |
| require 'json' | |
| if ARGV[0].to_s.start_with?("#") | |
| tag = CGI.escape(ARGV[0].to_s).sub(/\A%23/, "") | |
| else | |
| username = ARGV[0] | |
| end | |
| response = if username | |
| JSON.parse(open("https://www.instagram.com/#{username}/?__a=1").read) | |
| else | |
| JSON.parse(open("https://www.instagram.com/explore/tags/#{tag}/?__a=1").read) | |
| end | |
| Dir.mkdir(ARGV[0]) | |
| def media_tag(response) | |
| response["tag"]["media"] rescue response["user"]["media"] | |
| end | |
| while !media_tag(response)["nodes"].empty? | |
| media_tag(response)["nodes"].reject {|n| n['is_video'] }.each do |node| | |
| image_url = node['display_src'] | |
| file_name = "#{ARGV[0]}/#{image_url.split('/').last}" | |
| unless File.exists?(file_name) | |
| puts "Downloading #{file_name}..." | |
| IO.copy_stream(open(image_url), file_name) | |
| else | |
| puts "#{file_name} already exists, skipping it" | |
| end | |
| end | |
| if media_tag(response)["page_info"]["has_next_page"] | |
| end_cursor = media_tag(response)["page_info"]["end_cursor"] | |
| response = if username | |
| JSON.parse(open("https://www.instagram.com/#{username}/?__a=1&max_id=#{end_cursor}").read) | |
| else | |
| JSON.parse(open("https://www.instagram.com/explore/tags/#{tag}/?__a=1&max_id=#{end_cursor}").read) | |
| end | |
| else | |
| puts "Done!" | |
| break | |
| end | |
| end | |
| # Usage: | |
| # hashtag: ruby instrgram_image_downloader "#justinbieber" | |
| # user: ruby instagram_image_downloader justinbieber |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment