您好,登錄后才能下訂單哦!
小編給大家分享一下利用python爬取網易云音樂熱歌榜的案例,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
首先找到要下載的歌曲排行榜的鏈接,這里用的是:
https://music.163.com/discover/toplist?id=3778678
然后更改你要保存的目錄,目錄要先建立好文件夾,例如我的是保存在D盤-360下載-網易云熱歌榜文件夾內,就可以完成下載。
如果文件夾沒有提前建好,會報錯[Errno 2] No such file or directory。
代碼實現:
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" } self.baseurl = baseurl self.headers = head self.path = path def main(self): html = self.askurl() bs4 = self.analysis(html) name1 = self.matching(bs4) self.save(name1) 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("textarea") bs4 = str(bs4) return bs4 def matching(self, bs4): rule0 = re.compile(r'"name":"(.*?)","tns":[],"alias":[]') name0 = re.findall(rule0, bs4) str = "" for i in name0: str = str + "," + i str = str.replace("\xa0", " ") rule1 = re.compile(r'jpg,(.*?),(.*?)","id":(\d*)') name1 = re.findall(rule1, str) return name1 def save(self, name1): for j in name1: print("正在下載:" + j[1] + " - " + j[0] + "...") url = "http://music.163.com/song/media/outer/url?id=" + j[2] content = requests.get(url=url, headers=self.headers).content with open(self.path + j[1] + " - " + j[0] + ".mp3", "wb") as f: f.write(content) print(j[1] + " - " + j[0] + "下載完畢。\n") time.sleep(0.5) return if __name__ == "__main__": baseurl = "https://music.163.com/discover/toplist?id=3778678" # 要爬取的熱歌榜鏈接 path = "D:/360下載/網易云熱歌榜/" # 保存的文件目錄 demo0 = Music(baseurl, path) demo0.main() print("下載完畢")
看完了這篇文章,相信你對利用python爬取網易云音樂熱歌榜的案例有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。