吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 46676|回复: 217
收起左侧

[Python 转载] 【Python爬虫】【已更新】酷狗音乐Flac无损音乐下载地址获取

    [复制链接]
小涩席 发表于 2020-3-26 00:04
本帖最后由 小涩席 于 2020-3-28 16:49 编辑

如题:还是那句话,自从笔者这几天迷上听音乐以后,就到处找高质的音乐听,
奈何现在所有的高质音乐都不方便下载,结果就搞了一个下载酷狗音乐的代码,
把代码复制到Pycharm中运行就行了,结束后能够得到无损音乐的下载地址,
希望能够帮助到和我一样的同类人。
顺便问一下,有推荐好一点的耳机吗?垃圾耳机听起来效果不行。(手动难受)


# -*- coding : 'UTF-8' -*-
#  Author:XSX
# Python3.8 Pycharm

import requests
from urllib import parse
from GetRandomheader import Randomheader
import re
import json
import time

def URLDecode(text):
    Decode = parse.quote(text)
    print('正在查找【{}】的无损音乐------请等待'.format(text))
    return Decode

def GetitemInfo(Decodetext, headers):
    ItemInfos = []
    url1 = 'https://songsearch.kugou.com/song_search_v2?callback=jQuery1124047909927884881864_1584769239146&keyword={}&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1584769239150'.format(Decodetext)
    r = requests.get(url1, headers=headers)
    r.encoding = r.apparent_encoding
    JsonText = json.loads(r.text[43:-2])
    for i in JsonText["data"]["lists"]:
        contents = {}
        contents['SongName'] = i['SongName']
        contents['AlbumID'] = i['AlbumID']
        contents['FileHash'] = i['FileHash']
        contents['SQFileHash'] = i['SQFileHash']
        contents['HQFileHash'] = i['HQFileHash']
        contents['MvHash'] = i['MvHash']
        ItemInfos.append(contents)
    return ItemInfos

def GetDownLinks(ItemInfos, headers):
    try:
        DownLists = []
        for Iteminfo in ItemInfos:
            ID = Iteminfo['AlbumID']
            Hash = Iteminfo['SQFileHash']
            downurl = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery191006287980471670584_1584780452839&hash={0}&album_id={1}&dfid=3dTk9E0IfcV50gyRKr3OGZey&mid=0407f15d60c01b0ccb16bf2323d904b2&platid=4&_=1584780452841'.format(Hash, ID)
            time.sleep(3)
            r1 = requests.get(downurl, headers=headers)
            r1.encoding = r1.apparent_encoding
            DownLists.append(r1.text[42:-2].replace('\\', '').encode('utf8').decode('unicode_escape'))
        print('正在解析无损音质歌曲' + '\n' + '==========================' + '\n' + '说明:解析后无下载地址是因为该歌曲没有无损音质或需要付费下载' + '\n' + '==========================' + '>>>>>>>请稍后<<<<<<<')
        return DownLists
    except:
        pass

def GetSongLinks(DownLists):
    try:
        n = 0
        for DownList in DownLists:
            link = re.findall(r'.*' + '"play_url":"' + '(.*)' + '","authors"', str(DownList))
            n += 1
            print('正在解析第【{}】首无损音乐地址!'.format(n) + '\n' + '请点击下方链接下载保存音乐>>>>>>>>')
            print(link)
    except:
        pass

if __name__ == '__main__':
    head = Randomheader()
    GetSongLinks(GetDownLinks(GetitemInfo(URLDecode(input('请输入需要搜索的歌曲名称:')), head), head))





下面是更新后的解析代码,优化了解析速度,去除了无用的歌曲列表,旨在更快得到无损音质下载地址!!!!
有需求自取,运行方法一样。


# -*- coding : 'UTF-8' -*-
# python3.8 Pycharm
# Author : XSX

import requests
from urllib import parse
from GetRandomheader import Randomheader
import re
import json

def URLDecode(text):
    Decode = parse.quote(text)
    print('正在查找【{}】的无损音乐'.format(text))
    return Decode

def GetitemInfo(Decodetext, headers):
    ItemInfos = []
    url1 = 'https://songsearch.kugou.com/song_search_v2?callback=jQuery1124047909927884881864_1584769239146&keyword={}&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1584769239150'.format(Decodetext)
    r = requests.get(url1, headers=headers)
    r.encoding = r.apparent_encoding
    JsonText = json.loads(r.text[43:-2])
    for i in JsonText["data"]["lists"]:
        contents = {}
        contents['SongName'] = i['SongName']
        contents['AlbumID'] = i['AlbumID']
        contents['FileHash'] = i['FileHash']
        contents['SQFileHash'] = i['SQFileHash']
        contents['HQFileHash'] = i['HQFileHash']
        contents['MvHash'] = i['MvHash']
        ItemInfos.append(contents)
    return ItemInfos

def GetDownLinks(ItemInfos, headers):
    try:
        DownLists = []
        Iteminfo = ItemInfos[0]
        ID = Iteminfo['AlbumID']
        Hash = Iteminfo['SQFileHash']
        downurl = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery191006287980471670584_1584780452839&hash={0}&album_id={1}&dfid=3dTk9E0IfcV50gyRKr3OGZey&mid=0407f15d60c01b0ccb16bf2323d904b2&platid=4&_=1584780452841'.format(
            Hash, ID)
        r1 = requests.get(downurl, headers=headers)
        r1.encoding = r1.apparent_encoding
        DownLists.append(r1.text[42:-2].replace('\\', '').encode('utf8').decode('unicode_escape'))
        print('正在解析无损音质歌曲' + '\n' + '==========================' + '\n' + '说明:解析后无下载地址是因为该歌曲没有无损音质或需要付费下载' + '\n' + '==========================' + '\n' + '>>>>>>>请稍后<<<<<<<')
        return DownLists
    except:
        print("Process Error!")

def GetSongLinks(DownLists, text):
    try:
        for DownList in DownLists:
            link = re.findall(r'.*' + '"play_url":"' + '(.*)' + '","authors"', str(DownList))
            print('下发为【{}】无损音乐地址!'.format(text) + '\n' + '请点击下方链接下载保存音乐>>>>>>>>')
            print(link)
    except:
        pass

if __name__ == '__main__':
    head = Randomheader()
    text = input('请输入需要搜索的歌曲名称:')
    GetSongLinks(GetDownLinks(GetitemInfo(URLDecode(text), head), head), text)

音质1

音质1

音质2

音质2

代码运行后

代码运行后

免费评分

参与人数 16吾爱币 +14 热心值 +14 收起 理由
maomao862532 + 1 + 1 谢谢@Thanks!
大柚子 + 1 + 1 GetRandomheader模块找不到是什么原因呢?
12138bc + 1 我很赞同!
moshouhun + 1 + 1 用心讨论,共获提升!
唐小样儿 + 1 + 1 热心回复!
好甜emmm + 1 + 1 我很赞同!
Mandrake + 1 + 1 谢谢@Thanks!
jessd960212 + 1 + 1 我很赞同!
吾发如雪 + 1 + 1 谢谢@Thanks!
sail2000 + 1 + 1 谢谢@Thanks!
yeling16 + 1 谢谢@Thanks!
0001 + 1 热心回复!
众益科技 + 2 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
voila。 + 1 谢谢@Thanks!
sdaza + 1 我很赞同!
叼奶瓶逛酒吧 + 1 + 1 谢谢@Thanks!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

Zh1986 发表于 2020-4-3 18:49
你看看评论区一大片在问问题的就已经能证明了你的教程根本不是给大众用的,要不然也不会提出这么多的问题了,你就不想想论坛里面是有多少用户是做技术工作的??能懂软件和代码的寥寥无几,都是一些其它行业的人,隔行如隔山,你整教程又不整完整,用到什么工具?怎么用?你从头到尾的都在自说自话,这就是你不考虑实际用户知识水平有限,根本看不懂,所以你的热心也是寥寥无几。
老飞机 发表于 2020-3-28 22:45
本帖最后由 老飞机 于 2020-3-31 10:00 编辑

楼主,这个是我写的,解析接口的链接有时效性的
支持输入序号进行下载歌曲,就是接口很快失效

[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
import requests
import json
import os
from urllib.request import urlopen
from tqdm import tqdm
 
 
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}
 
music_list = []
 
def GetitemInfo():
    search = input("\033[1;45m请输入想搜索的歌\033[0m -==>:")
    url1 = 'https://songsearch.kugou.com/song_search_v2?callback=jQuery112404852453033521309_1585374178035&keyword={}&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1585374178039'.format(search)
    r = requests.get(url1, headers=headers)
    r.encoding = r.apparent_encoding
    JsonText = json.loads(str(r.text).strip('jQuery112404852453033521309_1585374178035(')[:-2])
    contents1 = []
    tone_quality = input("请选择音质;\033[1;45m1\033[0m = 无损音质 , \033[1;45m2\033[0m = 流畅音质 :\n")
    if tone_quality == "1":#高音质
        for i in JsonText["data"]["lists"]:
            quality_type = {}
            SQFileHash = i['SQFileHash']
            AlbumID = i['AlbumID']
            downurl = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery191012215974743400859_1585619590127&hash={}&album_id={}&dfid=0zI24KbQfP0cPOWD2MSu40&mid=415d42b77b039a48daf4f63d5b411ceb&platid=4&_=1585619590128'.format(SQFileHash, AlbumID)
            quality_type['type'] = '.flac'
            quality_type['url'] = downurl
            contents1.append(quality_type)
 
    if tone_quality == "2": #流畅音质
        for i in JsonText["data"]["lists"]:
            quality_type = {}
            AlbumID = i['AlbumID']
            FileHash = i['FileHash']
            downurl1 = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery191012215974743400859_1585619590127&hash={}&album_id={}&dfid=0zI24KbQfP0cPOWD2MSu40&mid=415d42b77b039a48daf4f63d5b411ceb&platid=4&_=1585619590128'.format(FileHash, AlbumID)
            quality_type['type'] = '.mp3'
            quality_type['url'] = downurl1
            contents1.append(quality_type)
    return contents1
 
def parser_json(data):
    ss = 0
    for data in data:
        url = data['url']
        ss += 1
        try:
            response = requests.get(url,headers=headers)
            if 'play_url' in response.text:
                music = {}
                json_TEXt = json.loads(str(response.text).strip("jQuery19108584376284926096_1585328784250(")[:-2])['data']
                url = json_TEXt['play_url']
                url1 = json_TEXt['play_backup_url']
                music_mane = json_TEXt['album_name']
                singer = json_TEXt['author_name']
                music["音乐链接"] = url
                music["歌曲名字"] = music_mane
                music["歌手"] = singer
                music['歌曲类型'] = data['type']
 
                print("音乐链接:",url)
                print("备份音乐链接:",url1)
                print("歌曲名字:",music_mane)
                print("歌手:",singer)
                print("下载歌曲的序号:","\033[1;45m {} \033[0m".format(ss))
                print("\033[1;45m=\033[0m"*41,"\033[1;45m分割线\033[0m","\033[1;45m=\033[0m"*41)
                music_list.append(music)
 
            else:
                print('\n该URL解析不了',"或者出现滑动验证提示:\nhttps://www.kugou.com/song/#hash=C9B86DA7FE6F500D72A68FF7A705E1E0&album_id=12855831")
            continue
 
        except Exception as e:
            print(e)
 
    if_download = input("请输入上面的\033[1;45m下载歌曲的序号\033[0m:")
 
    slice = music_list[int(if_download)-1:int(if_download)]
 
    download_from_url(slice)
 
def download_from_url(music_data):
    for data in music_data:
        url = data['音乐链接']
        music_mane = data['歌曲名字']
        singer = data['歌手']
        quality_type = data['歌曲类型']
 
        dst = singer + " - " +music_mane + quality_type
 
        file_size = int(urlopen(url).info().get('Content-Length', -1))
 
        if os.path.exists(dst):
            first_byte = os.path.getsize(dst)
        else:
            first_byte = 0
        if first_byte >= file_size:
            return file_size
        header = {"Range": "bytes=%s-%s" % (first_byte, file_size)}
        pbar = tqdm(
            total=file_size, initial=first_byte,
            unit='B', unit_scale=True, desc=dst)
        req = requests.get(url, headers=header, stream=True)
        with(open( dst, 'ab')) as f:
            for chunk in req.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
                    pbar.update(1024)
        pbar.close()
        return file_size
 
if __name__ == '__main__':
    parser_json(GetitemInfo())
老飞机 发表于 2020-3-28 14:35
楼主你看,跟你的歌曲是是一样的,解析不出来无损音质
image.png
IT_K 发表于 2020-3-26 07:24
厉害了我的哥
马克思 发表于 2020-3-26 00:53
耳机推荐网易云的HiFi
先有我后有天 发表于 2020-3-26 00:34
像这种的一般多久会失效
pop81835 发表于 2020-3-26 00:11
代码在哪里?要跟着敲一次吗
长河落 发表于 2020-3-26 01:07
建议加一个歌曲名称的爬取,直接把文件命名成歌曲-歌手的形式
yamisxu 发表于 2020-3-26 00:30
能爬索尼hires吗?
曼殊.沙华 发表于 2020-8-6 20:47
500以内首推shp9500,500到1000就7506和srh840,如果木耳这些个就够了再贵也没啥必要了,如果预算够请直接上大奥2代
wangzihang 发表于 2020-3-26 06:33
建议加一个歌曲名称的爬取,直接把文件命名成歌曲-歌手的形式
sharokku4869 发表于 2020-3-26 07:03
先感谢大佬分享这只爬虫,借走下音乐了,哈哈
zzs_70 发表于 2020-3-26 07:34
嗯,这个不错,有好听的歌曲听了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-4-23 11:17

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表