代码如下:
import requests
import json
# 引用requests,json模块url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp'headers = {'origin':'https://y.qq.com',# 请求来源,本案例中其实是不需要加这个参数的,只是为了演示'referer':'https://y.qq.com/n/yqq/song/004Z8Ihr0JIu5s.html',# 请求来源,携带的信息比“origin”更丰富,本案例中其实是不需要加这个参数的,只是为了演示'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',# 标记了请求从什么设备,什么浏览器上发出}for x in range(20):
# 伪装请求头params = {'ct':'24','qqmusic_ver': '1298','new_json':'1','remoteplace':'sizer.yqq.lyric_next','searchid':'48335540534966617','aggr':'1','cr':'1','catZhida':'1','lossless':'0','sem':'1','t':'7','p':str(x+1),'n':'10','w':'周杰伦','g_tk':'1714057807','loginUin':'0','hostUin':'0','format':'json','inCharset':'utf8','outCharset':'utf-8','notice':'0','platform':'yqq.json','needNewCode':'0'}res = requests.get(url, params = params)#下载该网页,赋值给resjson_music=res.json()# 使用json来解析res.textlist_music=json_music['data']['lyric']['list']# 一层一层地取字典,获取歌词的列表for music in list_music:#list_music是一个列表,x是它里面的元素print(music['content'].replace('\\n', ' '))#以content为键,查找歌词print("-----------------------------------------------------------------------------------------------------")
注意:
- music[‘content’]里面提取出来的歌词是带有“\n”的,所以需要通过replace()函数将其清除掉,.replace("\n",’ ')
- 关于字符串去除符号的更多内容,可以参考下这篇文章Python中字符串String去除出换行符(\n,\r)和空格的问题