【Python3爬蟲】網易雲音樂歌單下載

來源:互聯網
上載者:User

標籤:app   分享   結果   cep   pass   safari   text   需要   ade   

一、目標:  下載網易雲音樂熱門歌單

 

二、用到的模組:  requests,multiprocessing,re。

 

三、步驟:

  (1)頁面分析:首先開啟網易雲音樂,選擇熱門歌單,可以看到以下歌單列表,然後開啟開發人員工具

   因此我們需要請求的url就是https://music.163.com/discover/playlist,然後用requests.get()方法請求頁面,對於返回的結果,用Regex進行解析,得到歌單名字和歌單id,解析的Regex如下:

res = requests.get(url, headers=headers)
data = re.findall(‘<a title="(.*?)" href="/playlist\?id=(\d+)" class="msk"></a>‘, res.text)

  

  (2)得到歌單名字和歌單id後,構造歌單的url,然後模仿步驟(1)可以得到歌曲名字和歌曲id,解析的Regex如下:

re.findall(r‘<a href="/song\?id=(\d+)">(.*?)</a>‘, res.text)

  再得到歌曲id後,構造歌曲的url,然後用requests.get().content方法下載歌曲,歌曲的url構造方法如下:

"http://music.163.com/song/media/outer/url?id=%s" %(歌曲id)

 

  (3)由於部分歌曲的名字並不能作為檔案名稱儲存下來,所以用到了try...except,對於不能儲存為檔案名稱的歌曲,我選擇pass掉==

    

  (4)因為要下載多個歌單,一個歌單裡又有很多歌曲,所以用到了multiprocessing模組的Pool方法,提高程式啟動並執行效率。

 

四、具體代碼

  因為下載所有歌單會需要很長時間,所以我們先下載前三個歌單試試==

 1 import requests 2 import re 3 from multiprocessing import Pool 4  5 headers = { 6     ‘Referer‘: ‘https://music.163.com/‘, 7     "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 " 8                   "Safari/537.36" 9 }10 11 12 def get_page(url):13     res = requests.get(url, headers=headers)14     data = re.findall(‘<a title="(.*?)" href="/playlist\?id=(\d+)" class="msk"></a>‘, res.text)15 16     pool = Pool(processes=4)17     pool.map(get_songs, data[:3])18     print("下載完畢!")19 20 21 def get_songs(data):22     playlist_url = "https://music.163.com/playlist?id=%s" % data[1]23     res = requests.get(playlist_url, headers=headers)24     for i in re.findall(r‘<a href="/song\?id=(\d+)">(.*?)</a>‘, res.text):25         download_url = "http://music.163.com/song/media/outer/url?id=%s" % i[0]26         try:27             with open(‘music/‘ + i[1]+‘.mp3‘, ‘wb‘) as f:28                 f.write(requests.get(download_url).content)29         except FileNotFoundError:30             pass31         except OSError:32             pass33 34 35 if __name__ == ‘__main__‘:36     hot_url = "https://music.163.com/discover/playlist/?order=hot"37     get_page(hot_url)

 

五、運行結果

 

【Python3爬蟲】網易雲音樂歌單下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.