Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions examples/get_album_audio.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
import collections

import vk_api
from vk_api.audio import VkAudio


def main():
""" Пример отображения 5 последних альбомов пользователя """

login, password = 'login', 'password'
vk_session = vk_api.VkApi(login, password)

try:
vk_session.auth()
except vk_api.AuthError as error_msg:
print(error_msg)
return

vkaudio = VkAudio(vk_session)

albums = []
offset = 0

while True:
temp_albums = vkaudio.get_albums(owner_id='194957739', offset=offset)

if not temp_albums:
break

albums += temp_albums
offset += len(temp_albums)

print('\nLast 5:')
for album in albums[:5]:
print(album['title'])

# Ищем треки последнего альбома
print('\nSearch for', albums[0]['title'])
tracks = vkaudio.get(album_id=albums[0]['id'])

for n, track in enumerate(tracks, 1):
print('{}. {} {}'.format(n, track['title'], track['url']))


if __name__ == '__main__':
main()
67 changes: 60 additions & 7 deletions vk_api/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .audio_url_decoder import decode_audio_url
from .exceptions import AccessDenied

RE_AUDIO = re.compile(r'audio\d+_\d+_audios\d+')
RE_AUDIO = re.compile(r'audio[-\d]+_\d+_audios\d+')


class VkAudio:
Expand All @@ -16,15 +16,28 @@ class VkAudio:
def __init__(self, vk):
self._vk = vk

def get(self, owner_id, offset=0):
def get(self, owner_id=None, album_id=None, offset=0):
""" Получить список аудиозаписей пользователя

:param owner_id: ID владельца (отрицательные значения для групп)
:param album_id: ID альбома (отрицательные значения для групп)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ID альбомов тоже отрицательные?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

да, я писал же выше

:param offset: смещение
"""

if owner_id is None and album_id is None:
raise TypeError(
'get() missing 1 required argument: album_id or owner_id'
)
elif owner_id is not None and album_id is not None:
raise TypeError('get() too many arguments')

if album_id is not None:
url = 'https://m.vk.com/audio?act=audio_playlist{}'.format(album_id)
else:
url = 'https://m.vk.com/audios{}'.format(owner_id)

response = self._vk.http.get(
'https://m.vk.com/audios{}'.format(owner_id),
url,
params={
'offset': offset
},
Expand All @@ -33,12 +46,34 @@ def get(self, owner_id, offset=0):

if not response.text:
raise AccessDenied(
'You don\'t have permissions to browse {}\'s audio'.format(
'You don\'t have permissions to browse user\'s audio'
)

return scrap_data(response.text)

def get_albums(self, owner_id, offset=0):
""" Получить список альбомов пользователя

:param owner_id: ID владельца (отрицательные значения для групп)
:param offset: смещение
"""

response = self._vk.http.get(
'https://m.vk.com/audio?act=audio_playlists{}'.format(owner_id),
params={
'offset': offset
},
allow_redirects=False
)

if not response.text:
raise AccessDenied(
'You don\'t have permissions to browse {}\'s albums'.format(
owner_id
)
)

return scrap_data(response.text)
return scrap_albums(response.text)

def search_user(self, owner_id, q=''):
""" Искать по аудиозаписям пользователя
Expand Down Expand Up @@ -92,8 +127,7 @@ def scrap_data(html):

soup = BeautifulSoup(html, 'html.parser')
tracks = []

for audio in soup.find_all('div', {'class': 'audio_item ai_has_btn'}):
for audio in soup.find_all('div', {'class': 'audio_item'}):
ai_artist = audio.select('.ai_artist')
artist = ai_artist[0].text
link = audio.select('.ai_body')[0].input['value']
Expand All @@ -110,3 +144,22 @@ def scrap_data(html):
})

return tracks


def scrap_albums(html):
""" Парсинг списка альбомов из html странцы """

soup = BeautifulSoup(html, 'html.parser')
albums = []
for album in soup.find_all('div', {'class': 'audioPlaylistsPage__item'}):
link = album.select('.audioPlaylistsPage__itemLink')[0]['href']

albums.append({
'artist': album.select('.audioPlaylistsPage__author')[0].text,
'title': album.select('.audioPlaylistsPage__title')[0].text,
'plays': album.select('.audioPlaylistsPage__stats')[0].text,
'id': album['class'][1][25:],
'url': 'https://m.vk.com/audio?act=audio_playlist{}'.format(link)
})

return albums