python爬取qq音乐并保存
时间: 2023-10-13 12:07:48 浏览: 144
python爬取音乐
答案如下:
可以使用Python的requests库和BeautifulSoup库来爬取QQ音乐的数据,并使用Python的csv库将数据保存为csv文件。以下是一些示例代码:
```
import requests
from bs4 import BeautifulSoup
import csv
url = 'https://y.qq.com/portal/search.html#page=1&searchid=1&remoteplace=txt.yqq.top&t=song&w='
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 发送请求
response = requests.get(url, headers=headers)
# 解析html
soup = BeautifulSoup(response.text, 'html.parser')
# 获取歌曲列表
song_list = soup.select('.js_song')
# 遍历歌曲列表
for song in song_list:
# 获取歌曲id和名称
song_id = song.attrs['data-mid']
song_name = song.attrs['title']
# 根据歌曲id发送请求获取歌曲播放链接
url = 'https://u.y.qq.com/cgi-bin/musicu.fcg?data={"req":{"module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"5961496713","calltype":0,"userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"5961496713","songmid":["%s"],"songtype":[0],"uin":"0","loginflag":1,"platform":"20"}},"comm":{"uin":0,"format":"json","ct":24,"cv":0}}' % song_id
response = requests.get(url, headers=headers)
play_link = response.json()['req_0']['data']['midurlinfo'][0]['purl']
# 将歌曲id、名称和播放链接保存到csv文件中
with open('song_list.csv', mode='a+', encoding='utf-8', newline='') as file:
writer = csv.writer(file)
writer.writerow([song_id, song_name, play_link])
```
这段代码可以爬取QQ音乐的歌曲列表,并将每首歌曲的id、名称和播放链接保存到名为"song_list.csv"的csv文件中。请注意,网站的结构可能会更改,代码可能需要进行适当的修改才能正常工作。
阅读全文