- 在歌单页面打开控制台,输入
frames[0].document.getElementsByTagName('tbody')[0].innerHTML
复制 HTML - 安装库并运行 Python 脚本,粘贴 HTML 回车
Created
June 29, 2021 03:37
-
-
Save AllanChain/6e9bd15e0e90528c6d0898dcc83251b9 to your computer and use it in GitHub Desktop.
网易云音乐歌单下载,保留 ID3 属性
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bs4 import BeautifulSoup | |
from pathlib import Path | |
from dataclasses import dataclass | |
import urllib.request | |
import re | |
from unicodedata import normalize | |
from mutagen.mp3 import EasyMP3 | |
DOWNLOAD_TEMPLATE = "http://music.163.com/song/media/outer/url?id=%s.mp3" | |
ROOT = Path(__file__).parent | |
@dataclass | |
class Music: | |
id: str | |
title: str | |
filename: str | |
artist: str | |
album: str | |
def download_mp3(music: Music): | |
mp3file = ROOT / "mp3" / f"{music.filename}.mp3" | |
if mp3file.exists(): | |
print(f"{music.title} is already download") | |
return | |
url = DOWNLOAD_TEMPLATE % music.id | |
print(f"Downloading {music.title}") | |
data = urllib.request.urlopen( | |
urllib.request.Request( | |
url, | |
headers={ | |
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36" | |
}, | |
) | |
).read() | |
if len(data) < 1000: | |
print("Error:", data) | |
return | |
with open(mp3file, "wb") as f: | |
f.write(data) | |
mp3meta = EasyMP3(mp3file) | |
mp3meta["album"] = music.album | |
mp3meta["albumartist"] = music.artist | |
mp3meta["artist"] = music.artist | |
mp3meta["title"] = music.title | |
mp3meta.save() | |
def create_filename(title): | |
title = re.sub(r"\(.*\)$", "", title).strip() | |
title = re.sub(r"[\\/:*\"<>?|]", " ", title).strip(' -.') | |
return title | |
def main(html): | |
soup = BeautifulSoup(html, "html.parser") | |
for tr in soup.find_all("tr"): | |
id, title, _, artist, album = tr.find_all("td") | |
music = Music( | |
id=id.span["data-res-id"], | |
title=normalize("NFKD", title.b["title"]), | |
filename=normalize("NFKD", create_filename(title.b["title"])), | |
artist=normalize("NFKD", artist.span["title"]), | |
album=normalize("NFKD", album.a["title"]), | |
) | |
download_mp3(music) | |
# print(music) | |
if __name__ == "__main__": | |
(ROOT / "mp3").mkdir(exist_ok=True) | |
main(input("> )) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mutagen | |
beautifulsoup4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment