写一段python代码爬取并下载QQ音乐周杰伦的20首歌
时间: 2024-02-15 11:34:16 浏览: 136
由于QQ音乐官方网站进行了反爬虫限制,因此本文提供的代码仅供学习参考,不保证一定能够成功运行。
```python
import requests
from bs4 import BeautifulSoup
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'}
url = 'https://y.qq.com/n/yqq/singer/0025NhlN2yWrP4.html'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
song_list = soup.find_all('span', class_='songlist__songname_txt')
for i in range(20):
song_name = song_list[i].get_text()
song_id = song_list[i].find('a')['href'].split('/')[-1].split('.')[0]
download_url = f'https://u.y.qq.com/cgi-bin/musicu.fcg?data=%7B%22req_0%22%3A%7B%22module%22%3A%22vkey.GetVkeyServer%22%2C%22method%22%3A%22CgiGetVkey%22%2C%22param%22%3A%7B%22guid%22%3A%221234567890%22%2C%22songmid%22%3A%5B%22{song_id}%22%5D%2C%22songtype%22%3A%5B0%5D%2C%22uin%22%3A%220%22%2C%22platform%22%3A%2220%22%2C%22loginflag%22%3A1%2C%22hostUin%22%3A%220%22%7D%7D%2C%22comm%22%3A%7B%22uin%22%3A0%2C%22format%22%3A%22json%22%2C%22ct%22%3A24%2C%22cv%22%3A0%7D%7D'
download_response = requests.get(download_url, headers=headers)
download_json = download_response.json()
download_link = download_json['req_0']['data']['midurlinfo'][0]['purl']
if download_link:
with open(f'{song_name}.m4a', 'wb') as f:
f.write(requests.get(f'https://isure.stream.qqmusic.qq.com/{download_link}', headers=headers).content)
print(f'{song_name}下载成功')
else:
print(f'{song_name}下载失败')
```
解析:
首先,我们使用requests库和BeautifulSoup库对QQ音乐周杰伦的歌曲页面进行请求和解析,得到歌曲列表。
然后,我们通过循环遍历歌曲列表,获取每首歌的名称和ID,并使用下载链接API获取每首歌的下载链接。
最后,我们使用requests库下载每首歌,并将其保存到本地。如果下载链接获取失败,则打印下载失败的提示信息。
阅读全文