用python实现音乐下载

前言

本文背景

最近对音乐比较有需求,想着用自己学的python来实现一下下载需求,
真的是拿着锤子在满世界找钉子,**文末附全部代码**

声明:

 本文仅作技术交流,禁止用于其他非法途径
 本文2023年9月15日是可用的,但是爬虫与反爬一直在博弈哦

1、寻找播放链接

首先我们要知道,只要能够拿到音乐播放的链接,再构造请求就能实现下载,那我们来找找音乐链接在哪吧,打开浏览器的检查,找啊找,终于找到你了,我们按照图上的关键字进行搜索很快就能找到播放地址
在这里插入图片描述

既然播放地址在返回的包里,那我们只要模拟发送请求就能拿到这个包,进而实现下载了

2、分析请求参数

接下来我们来看看请求参数,经过反复的测试,发现其中mid、、及encode_album_audio_id是会变的,其中encode_album_audio_id是音乐的id,“”是时间戳,mid是经过加密的一串字符
在这里插入图片描述

(一) 如何获取encode_album_audio_id参数

在这里插入图片描述

这个参数很好获取,在歌曲页、榜单页里按照图片上的步骤就能找到

(二)如何生成时间戳‘_'参数


import time

timestamp = int(time.time() * 1000)
_ = str(timestamp)

(三)如何生成mid参数

在逆向方面我用的比较少,所以存在许多不足,借鉴了一下其他大神的博客,这个参数是可以通过python直接生成的,省去了扣js代码的麻烦,真是太赞了,此处借鉴了不想掉头发大神的文章,想了解分析过程的可以去这里,博客传送门

import random,hashlib

def gen_md5(word):
    word = ''.join([x for x in word])
    encode_word = word.encode('utf-8')
    return hashlib.md5(encode_word).hexdigest()
def guid():
    num = 1 + random.random()
    res = hex(int(65536 * num))[3:]
    return res

def get_GUID():
    GUID = guid() + guid() + "-" + guid() + "-" + guid() + "-" + guid() + "-" + guid() + guid() + guid()
    return GUID
# 获取mid参数
def get_mid():
    GUID = get_GUID()
    mid = gen_md5(GUID)
    return mid

到这里我们的请求参数就已经全部实现了

3、构造请求参数,获取下载链接

接下来我们就开始模拟请求了,检验一下我们的代码是否能跑



# 这是一个获取音乐播放链接的函数
def get_Playurl(song_id):
    timestamp = int(time.time() * 1000)
    dfid = '-'
    mid = get_mid()
    encode_album_audio_id = song_id
    # headers = {
    #     "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
    # }
    url = '音乐url'
    try:
        r = requests.get(url, headers=get_headers())
        r.encoding = r.apparent_encoding
        head = len('jQuery191089893143860232_1694668397872(')
        data = json.loads(r.text[head:-2])
        song_name = data['data']['song_name']
        author_name = data['data']['author_name']
        song_name = f'{song_name}-{author_name}'
        play_url = data['data']['play_url']
        print(f'成功获取:{song_name},{play_url}')
        return song_name,play_url
    except:
        print('Error:获取play_url,song_name出错,请检查各项请求参数是否有更新')
        pass
    return song_name, play_url

4、下载

下载部分也很简单,需要把自己的cookie传进去就是了,cookie如何获取呢
在这里插入图片描述
这是图中输入的代码

javascript:alert(document.cookie)

下载函数

# 这是一个下载函数,提供歌曲id就能下载,
#使用前记得先把文件保存位置改成你想要保存的位置,或者新建一个music文件夹

def Download(song_id):
    song_name,play_url = get_Playurl(song_id)
    with open(f'./music/{song_name}.mp3','wb') as file:
        try:
            r = requests.get(play_url,headers=get_headers())
            if r.status_code == 200:
                file.write(r.content)
                print(f'{song_name}  下载成功')
        except:
            print(f'Error:{song_name}  下载失败,请检查网络或请求网址是否正确')
            

UserAgent.py

通过随机请求头实现简单的反爬


import random

user_agent = [
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
    "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0",
    "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
    "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
    "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
    "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
    "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
    "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
    "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    "MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    "Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
    "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
    "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
    "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0",
    "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)",
    "UCWEB7.0.2.37/28/999",
    "NOKIA5700/ UCWEB7.0.2.37/28/999",
    "Openwave/ UCWEB7.0.2.37/28/999",
    "Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/999",
    # iPhone 6
	"Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25",
    # 新版移动ua
    "Mozilla/5.0 (Linux;u;Android 4.2.2;zh-cn;) AppleWebKit/534.46 (KHTML,like Gecko) Version/5.1 Mobile Safari/10600.6.3 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"
]

# 随机获取一个请求头
def get_headers():

    return {
        'User-Agent': random.choice(user_agent),
    }

5、成果展示

在这里插入图片描述

在这里插入图片描述

6、全部代码

百度网盘
提取码:e8s9

7、写在最后

使用指南:

拿到代码后需要做哪些修改?

cookie改成你的
文件下载位置改为你的或者新建music文件夹
自己找榜单之后才能批量下载

感谢你看到了最后,我们下次见

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
使用 Python 实现下载免费音乐的过程需要用到第三方库,比如 `requests` 和 `beautifulsoup4`。 1. 首先,我们需要从网站上获取音乐下载链接。一个比较好的网站是 https://www.sq688.com/,我们可以使用 `requests` 库来获取网页的内容: ```python import requests url = 'https://www.sq688.com/' res = requests.get(url) html = res.text ``` 2. 接下来,我们需要使用 `beautifulsoup4` 库来解析 HTML,从中获取音乐下载链接。具体代码如下: ```python from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') music_list = soup.find_all('div', class_='music-list')[0] music_links = music_list.find_all('a') for link in music_links: music_url = link['href'] print(music_url) ``` 3. 最后,我们可以使用 `requests` 库下载音乐: ```python import os if not os.path.exists('music'): os.mkdir('music') for link in music_links: music_url = link['href'] music_name = link.text res = requests.get(music_url) with open('music/{}.mp3'.format(music_name), 'wb') as f: f.write(res.content) ``` 完整代码如下: ```python import requests from bs4 import BeautifulSoup import os url = 'https://www.sq688.com/' res = requests.get(url) html = res.text soup = BeautifulSoup(html, 'html.parser') music_list = soup.find_all('div', class_='music-list')[0] music_links = music_list.find_all('a') if not os.path.exists('music'): os.mkdir('music') for link in music_links: music_url = link['href'] music_name = link.text res = requests.get(music_url) with open('music/{}.mp3'.format(music_name), 'wb') as f: f.write(res.content) ``` 注意:请勿在未经授权的情况下下载版权受保护的音乐

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值