仅供学习参考html
Python爬取网易云音乐网易云音乐歌手歌曲和歌单,并下载到本地python
不少人学习python,不知道从何学起。
不少人学习python,掌握了基本语法事后,不知道在哪里寻找案例上手。
不少已经作案例的人,殊不知道如何去学习更加高深的知识。
那么针对这三类人,我给你们提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:101677771服务器
①找到要下载歌手歌曲的连接,这里用的是:
https://music.163.com/#/artist?id=10559
要提早建好保存文件夹:path1 = "D:/360下载/网易云音乐/1/"
而后更改你要保存的目录,目录要先创建好文件夹,例如个人是保存在D盘-360下载-网易云音乐-1文件夹内,就能够完成下载。若是文件夹没有提早建好,会报错[Errno 2] No such file or directory。学习
②找到要下载歌单的连接,这里用的是:
https://music.163.com/#/playlist?id=5175828159
要提早建好保存文件夹:path2 = "D:/360下载/网易云音乐/2/"
只能下载前面10首。
以后的歌曲信息服务器不给数据,没法拿到歌曲id。
我尝试使用网易云音乐PC端(能够加载歌单全部歌曲),用fiddler进行抓包,是POST请求,经过模拟请求,获得的response是乱码,尝试utf-八、gbk、gbk2312等解码也是乱码。应该客户端拿到数据是加密的,我没有找到其解密方式。只能使用模拟网页请求拿取歌单前面10首歌曲。
如有好的想法,能够一块儿探讨。
代码写于:2020.8.23ui
③要下载热歌榜全部歌曲,请查看我前一个发布内容加密
from urllib import request from bs4 import BeautifulSoup import re import requests import time class Music(object): def __init__(self, baseurl, path): head = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36" } baseurl = baseurl.replace("#/", "") self.baseurl = baseurl self.headers = head self.path = path def main(self): html = self.askurl() bs4 = self.analysis(html) id = self.matching(bs4) self.save(id) def askurl(self): req = request.Request(url=self.baseurl, headers=self.headers) response = request.urlopen(req) html = response.read().decode("utf-8") return html def analysis(self, html): soup = BeautifulSoup(html, "html.parser") bs4 = soup.find_all("li") bs4 = str(bs4) return bs4 def matching(self, bs4): rule = re.compile(r'href="/song\?id=(\d*?)"', re.S) id = re.findall(rule, bs4) return id def save(self, id): for i in id: url = "https://music.163.com/song?id=" + i req = request.Request(url=url, headers=self.headers) response = request.urlopen(req) html = response.read().decode("utf-8") soup = BeautifulSoup(html, "html.parser") bs4 = soup.find_all("title") bs4 = str(bs4) rule = re.compile(r'<title>(.*?) - (.*?) - 单曲 - 网易云音乐</title>', re.S) name = re.findall(rule, bs4) name = name[0] singername = name[1].replace(r"/", "_") print("正在下载:" + name[0] + " - " + singername + "……") saveurl = "http://music.163.com/song/media/outer/url?id=" + i content = requests.get(url=saveurl, headers=self.headers).content with open(self.path + name[0] + " - " + singername + ".mp3", "wb") as f: f