7、爬虫-爬取音乐

1、查找请求音乐播放的请求 url地址:以酷我音乐为例

  拿到url 对url进行分析 :https://www.kuwo.cn/api/v1/www/music/playUrl?mid=326968713&type=music&httpsStatus=1&reqId=bf6ff0b0-acb0-11ee-bf9b-c39de8563da8&plat=web_www&from=

  mid = 不同歌曲的id

  type = 音乐的类型、type=mp3 

  httpsStatus  状态码

  reqId  不知道作用

2、查找html里不同音乐 的标签里有无类型 id的数字

 

更换url的mid试试:看是否能对应歌曲

https://www.kuwo.cn/api/v1/www/music/playUrl?mid=330465682&type=music&httpsStatus=1&reqId=bf6ff0b0-acb0-11ee-bf9b-c39de8563da8&plat=web_www&from=

将type改为 type=mp3就可以下载付费音乐了

 

"""
下载会员音乐
"""

import requests
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
url_base = "https://www.kuwo.cn/api/v1/www/music/playUrl?mid=%s&type=music&httpsStatus=1&reqId=bf6ff0b0-acb0-11ee-bf9b-c39de8563da8&plat=web_www&from="
music_id = 330465682

url = url_base % music_id   #拼接真正的url mid=%s   %s=music_id

response = requests.get(url,headers=headers)

#取到json格式的文本、里面包含音乐连接
result = response.json()

#提取播放连接
play_url = result.get("data").get("url")

#下载音乐
response_music = requests.get(play_url,headers=headers)
with open("晴天.mp3","wb") as file:
    file.write(response_music.content)


#################################封装成函数################################
def download_music(music_id,music_name):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
    }


    url_base = "https://www.kuwo.cn/api/v1/www/music/playUrl?mid=%s&type=music&httpsStatus=1&reqId=bf6ff0b0-acb0-11ee-bf9b-c39de8563da8&plat=web_www&from="
    url = url_base % music_id  # 拼接真正的url mid=%s   %s=music_id
    response = requests.get(url, headers=headers)

    # 取到json格式的文本、里面包含音乐连接
    result = response.json()

    # 提取播放连接
    play_url = result.get("data").get("url")

    # 下载音乐
    response_music = requests.get(play_url, headers=headers)
    with open("%s.mp3" %music_name, "wb") as file:
        file.write(response_music.content)

if __name__ == '__main__':
    #调用函数下载
    download_music(118980, "晴天")
posted @ 2024-07-01 22:24  little小新  阅读(65)  评论(0编辑  收藏  举报