python爬千千音樂

來源:互聯網
上載者:User

標籤:訪問   .json   互連網   傳遞參數   with open   findall   min   odi   text   

類比瀏覽器,訪問互連網資源,根據所寫的規則,下載所需的音樂資料!

原始碼查看:在更多工具裡的開發人員工具(shift+ctrl+I 或f12)

在Google瀏覽器中登入千千音樂 http://music.taihe.com

在pycharm寫代碼

在Terminal中輸入pip install requests斷行符號即安裝requests

程式碼:

import requests
import re


#第一步 擷取歌曲ids
search_api =‘http://music.taihe.com/search‘
#搜尋的關鍵字,傳遞參數,通過字典構造
keyword = {‘key‘:‘阿蘭‘}
#發送請求
#get請求 params 是傳遞的get參數
response=requests.get(search_api,params=keyword)
#取出html的源碼
response.encoding=‘utf-8‘
html = response.text
#通過Regex擷取id
ids=re.findall(r‘{"id":"(\d+)"‘,html)
print(ids)
#第二步 擷取歌曲的資訊
mp3_info_api =‘http://play.taihe.com/data/music/songlink‘
data ={
‘songIds‘: ‘,‘.join(ids),
‘hq‘: 0,
‘type‘: ‘m4a,mp3‘,
‘rate‘: ‘‘,
‘pt‘: 0,
‘flag‘: -1,
‘s2p‘: -1,
‘prerate‘: -1,
‘bwt‘: -1,
‘dur‘: -1,
‘bat‘: -1,
‘bp‘: -1,
‘pos‘: -1,
‘auto‘: -1
}
#data就是post的參數
res = requests.post(mp3_info_api,data=data)
#返回的資料是json格式 直接調用json方法,轉成字典
info = res.json()

#第三步 去下載歌曲
#根據資料的結構,擷取歌曲的資訊
song_info =info[‘data‘][‘songList‘]
#迴圈
for song in song_info:
#根據資料結構擷取資訊
#歌名
song_name = song[‘songName‘]
#mp3地址
song_link = song[‘songLink‘]
#格式
for_mat = song[‘format‘]
#歌詞地址
lrclink = song[‘lrcLink‘]
# print(song_name,song_link,for_mat,lrclink)
#下載mp3
if song_link:#有可能沒有地址
song_res =requests.get(song_link)
with open(‘%s.%s‘ % (song_name,for_mat),‘wb‘)as f:
f.write(song_res.content)
print(song_link)

#下載歌詞
if lrclink:
lrc_response = requests.get(lrclink)
#寫檔案
with open(‘%s,lrc‘ % song_name, ‘w‘)as f:
f.write(lrc_response.text)

 

  

python爬千千音樂

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.