Skip to content

Instantly share code, notes, and snippets.

@vadim8kiselev
Last active March 18, 2016 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vadim8kiselev/a730fbbb9d1e79024c4d to your computer and use it in GitHub Desktop.
Save vadim8kiselev/a730fbbb9d1e79024c4d to your computer and use it in GitHub Desktop.
'''
Photo downloader
'''
import json
import urllib2
from urllib import urlencode
import os
rules = {'0':'profile', '00':'wall', '000':'saved', '0000':'graffiti'}
def call_public_api(method, params):
'''
Get json from public vk api request
'''
url = "https://api.vk.com/method/%s?%s" % (method, urlencode(params))
return json.loads(urllib2.urlopen(url).read())
def get_photos(owner_id, album_id):
'''
Get list of links from album
'''
try:
# Mapping of official albums
if album_id[0] == '0':
album_id = rules[album_id]
photos = call_public_api('photos.get', [('owner_id', owner_id), ('album_id', album_id)])
return [link['src_big'] for link in photos['response']]
except (KeyError, IndexError) as e:
return []
def get_album_name(owner_id, album_id):
'''
Get name of album
'''
try:
if album_id[0] == '0':
return owner_id + '_' + rules[album_id]
else:
album = call_public_api('photos.getAlbums', [('owner_id', owner_id), ('album_ids', album_id)])
return album['response'][0]['title']
except (KeyError, IndexError) as e:
return owner_id + '_' + album_id
url = raw_input('Enter the link to the album: ')
if url.find('?') != -1 and url.find('?') > url.rfind('_'):
url = url[:url.find('?')]
owner_id = url[url.find('album') + 5 : url.rfind('_')]
album_id = url[url.rfind('_') + 1 :]
album_name = get_album_name(owner_id, album_id)
links = get_photos(owner_id, album_id)
try:
if links:
if not os.path.isdir(album_name):
os.makedirs(album_name)
for link in links:
path = album_name + '/' + link[link.rfind('/') + 1 :]
photo = urllib2.urlopen(link).read()
with open(path, 'wb') as target_file:
target_file.write(photo)
print 'Downloaded:', link
print 'Photos saved in {0}'.format(os.getcwd() + '/' + album_name)
else:
print 'Incorrect url'
except KeyboardInterrupt:
print 'Downloading was stopped'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment