美文网首页
酷狗音乐 python3+requests下载

酷狗音乐 python3+requests下载

作者: Leo_23 | 来源:发表于2017-09-24 18:02 被阅读144次

    下午折腾了下酷狗音乐的下载,下面代码纯属练练手,请尊重搜狗的音乐版权!下载后请立即删除!

    gist 链接 前往 gist


    #!/usr/bin/env python

    # -*- coding: utf-8 -*-

    __author__ ='Leo'

    __date__ ='2017/9/24'

    '''

    告白气球

    记录坑:

    1.第一次请求拿到歌曲的hash值

    2.拿到hash之后是要去请求 http://www.kugou.com/yy/index.php?r=play/getdata&hash=3C3D93A5615FB42486CAB22024945264

    带上hash值,最后拿到 .mp3 路径,愉快的下载吧

    request url:

    http://songsearch.kugou.com/song_search_v2?keyword=告白气球&page=1&pagesize=30&platform=WebFilter&privilege_filter=0

    response:

    {

    "data":

    "lists": [

    {

    "SongName": "告白气球",

    "FileHash": 3C3D93A5615FB42486CAB22024945264    # 这是想要的

    }

    '''

    importos

    importrequests

    classMusicFile(object):

    def__init__(self,music_name):

    k = KuGouMusicSearch(music_name)# 酷狗音乐

    song_name,song_ext_name,file_hash = k.search_music()

    music_file_path = os.path.join(os.path.dirname(__file__),"music")

    self.music_file = os.path.join(music_file_path,("%s.%s"% (music_name,song_ext_name)))

    self.url =self.find_download_url(file_hash)# 获取真正的下载url

    if notos.path.exists(music_file_path):# 不存在目录

    os.mkdir(music_file_path)

    if notos.path.exists(self.music_file):# 不存在文件

    f =open(self.music_file,'w')

    f.close()

    self.download_music_to_file()

    defdownload_music_to_file(self):

    chunk_size =1024*1024

    result = requests.get(self.url,stream=True)

    withopen(self.music_file,"wb")asfd:

    forchunkinresult.iter_content(chunk_size=chunk_size):

    fd.write(chunk)

    @staticmethod

    deffind_download_url(file_hash):

    url ="http://www.kugou.com/yy/index.php?r=play/getdata&hash=%s"% file_hash

    response_json = requests.get(url).json()

    download_url = response_json["data"]["play_url"]

    returndownload_url

    classKuGouMusicSearch(object):

    def__init__(self,music_name):

    self.music_name = music_name

    defsearch_music(self):

    request_url ="http://songsearch.kugou.com/song_search_v2?"\

    "keyword=%s"\

    "&page=1&pagesize=30&platform=WebFilter&privilege_filter=0"% (self.music_name)

    response_json = requests.get(request_url).json()

    song = response_json["data"]["lists"][0]# 默认取第一个

    song_name = song["SongName"]

    song_ext_name = song["ExtName"]# 后缀 .mp3

    song_file_hash = song["FileHash"]# file hash, 为下载做准备

    returnsong_name,song_ext_name,song_file_hash

    if__name__ =='__main__':

    m = MusicFile("告白气球")

    相关文章

      网友评论

          本文标题:酷狗音乐 python3+requests下载

          本文链接:https://www.haomeiwen.com/subject/wvtlextx.html