Skip to content

Instantly share code, notes, and snippets.

@theasder
Last active November 26, 2021 17:07
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save theasder/73c3f0a9270ebe611a80 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import ast
import re
def get_items_of_post(address):
url = "https://api.vk.com/method/wall.getById?posts=" + address + "&extended=1&copy_history_depth=2"
response = urllib2.urlopen(url)
text = response.read()
# переводим из текста в словарь
post_info = ast.literal_eval(text)
if post_info['response']['wall'] == []:
return []
else:
return post_info['response']['wall'][0]['attachments']
address = raw_input("Enter string of two right numbers of url of post\n")
music = get_items_of_post(address)
for attachment in music:
type_of_attachment = attachment['type']
if type_of_attachment != 'audio':
pass
else:
artist = attachment[type_of_attachment]['artist']
title = attachment[type_of_attachment]['title']
name_of_file = artist + ' - ' + title + '.mp3'
url = attachment[type_of_attachment]['url']
if url == '': # предусмотрен случай, когда аудиозапись удалена из общего доступа
print name_of_file + " was removed from public access"
continue
url = re.sub('\\\\\/', '/', url) # вместо простых слэшей изначально записываются `\\/`, поэтому нужно их заменить на просто слэши во всей строке
url = re.sub('\?.*', '', url) # убираем все символы после расширения `.mp3`, они нам не нужны
response = urllib2.urlopen(url)
f = open(name_of_file, 'w')
f.write(response.read())
print name_of_file + " was downloaded" # оповещаем о том, что файл успешно скачался
@gEndelf
Copy link

gEndelf commented Jul 28, 2014

Небольшие пожелания к коду :)

закрывать файл после загрузки

with open(name_of_file, 'w') as f:
   f.write(response.read())

не лучший способ конкатенации строк

artist + ' - ' + title + '.mp3'

if post_info['response']['wall'] == []:
   return []
else:
   return post_info['response']['wall'][0]['attachments']

может быть заменено на

attachments = post_info['response']['wall'][0]['attachments'] if post_info['response']['wall'] else []

Copy link

ghost commented Jan 22, 2015

На Windows 7 скрипт скачал музыку, но она воспроизводилась некорректно. Запустил скрипт на Linux -- все работает отлично!

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