Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Downloading images from imgur album
- Get the json data, and from that we can find the number of images in the album
- Finds the image type as well (jpg or png) so we dont have to hardcode it
- Saves all the images into the a folder with the name of the album code
- e.g The 615 images in "https://imgur.com/gallery/oEX2D" will be saved in a folder
- called 'oEX2D', and numbered sequentially as 'image0.type', 'image1.type', ...
- '''
- import requests
- import json
- import re
- import os
- import time
- def getJsonData(imgur_album_url):
- print('Getting json data from', imgur_album_url, '...')
- json_url = imgur_album_url + '.json'
- page_data = requests.get(json_url)
- json_data = page_data.text
- print('Data retrieved.\n')
- return json_data
- def getAlbumSize(json_data):
- print('Getting number of images in album.')
- album_size = 0
- data = json.loads(json_data)
- album_size = data['data']['image']['num_images']
- print('There are', album_size, 'images in the album.\n')
- return album_size
- # Downloading an image from an url and choosing the name to be downloaded as
- def downloadImageFromUrl(image_url, file_name):
- with open(file_name, 'wb') as handle:
- response = requests.get(image_url, stream=True)
- for block in response.iter_content(1024):
- handle.write(block)
- def main():
- json_data = getJsonData('https://imgur.com/gallery/oEX2D')
- album_size = getAlbumSize(json_data)
- data = json.loads(json_data)
- image_type = data['data']['image']['ext']
- list_images = data['data']['image']['album_images']['images']
- album_code = data['data']['image']['hash']
- print('Creating folder for images.')
- os.mkdir(album_code)
- print('Folder', album_code, 'created.\n')
- print('Downloading images ...')
- for i, image_info in enumerate(list_images):
- image_code = image_info['hash']
- image_url = 'https://i.imgur.com/' + image_code + image_type
- file_name = album_code + '/image' + str(i) + image_type
- downloadImageFromUrl(image_url, file_name)
- print('Downloaded image from ', image_url, 'as', file_name)
- time.sleep(0.3)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement