python 爬虫爬取酷我音乐
发布日期:2021-05-18 11:03:58 浏览次数:24 分类:精选文章

本文共 2604 字,大约阅读时间需要 8 分钟。

Python 爬虫爬取酷我音乐

1)观察最先的请求头部报文

打开 Chrome 开发者工具,快捷键为 F12。进入开发者工具后,点击网络标签,选择之前的请求查看详细报文。在报文中关注以下三个字段:

  • Cookie:记录用户身份信息,用于身份验证。
  • csrf:防止跨站请求伪造攻击,缺少此值会导致请求失败。
  • User-Agent:模拟浏览器,需自行设置为常见浏览器的 User-Agent。

2)点击一首歌曲查看其请求报文

进入“media”目录,找到最新的音乐文件。查看其请求报头,可以看到资源名称“2199540768.mp3”,对应的请求链接为:

https://win-web-nf01-sycdn.kuwo.cn/64daa3f0495beb23ff0ffd4ec87cba8c/6052dbd5/resource/n1/32/15/2199540768.mp3

在搜索框中输入资源名称,结果页面显示的 URL 即为请求资源的链接:

http://kuwo.cn/url?format=mp3&rid=3462803&response=url&type=convert_url3&from=web&t=1616042964971&httpsStatus=1&reqId=5031d9d0-87a5-11eb-9d7b-25dfbbe74103

核心请求链接为:http://kuwo.cn/url?,其余参数为请求数据。通过分析请求报文发现,ridt 是关键字段,其中 t 为时间戳。

通过搜索 rid,可以找到对应的播放列表信息。请求 URL 为:

http://kuwo.cn/api/www/playlist/playListInfo?

提交内容如下:

format=mp3&rid=3462803&response=url&type=convert_url3&from=web&t=1616042964971&httpsStatus=1&reqId=5031d9d0-87a5-11eb-9d7b-25dfbbe74103

爬虫思路

  • 先请求 http://kuwo.cn/api/www/playlist/playListInfo?,获取播放列表。
  • 遍历 musiclist,获取每首歌的 rid
  • 构造请求参数,包含时间戳 t,并发送请求到 http://kuwo.cn/url?
  • 提取返回的 MP3 链接,下载并存储音乐文件。
  • 代码示例

    import requestsimport timeurl = "http://kuwo.cn/api/www/bang/bang/musicList?"url1 = "http://kuwo.cn/url?"header = {    'Accept': 'application/json, text/plain, */*',    'Accept-Encoding': 'gzip, deflate',    'Accept-Language': 'zh-CN,zh;q=0.9',    'Connection': 'keep-alive',    'Cookie': '自行找寻',    'csrf': '自行找寻',    'Host': 'kuwo.cn',    'Referer': 'http://kuwo.cn/search/list?key=%E5%91%A8%E6%9D%B0%E4%BC%A6',    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',}parameters = {    'bangId': '93',    'pn': '1',    'rn': '30',    'httpsStatus': '1',    'reqId': '473439b0-873a-11eb-a335-8dc7ebaa4a54',}music = requests.get(url=url, headers=header, params=parameters)music = music.json()music = music['data']['musicList']for i in music:    time.sleep(2)    name = i['name']    rid = i['rid']    t = int(time.time()) * 1000    parameters2 = {        "format": "mp3",        "rid": rid,        "response": "url",        "type": "convert_url3",        "from": "web",        "t": t,        "httpsStatus": "1",        "reqId": "自行找寻"    }    music_o = requests.get(url=url1, headers=header, params=parameters2)    with open('要存放的目录路径' + name + '.mp3', mode='wb') as f:        url3 = music_o.json()['url']        music = requests.get(url3)        f.write(music.content)        f.close()        print("爬取" + name + ".mp3" + "完成")

    小技巧

    • 使用 Notepad++ 的搜索替换功能,输入正则表达式 (.*?):(.*) 替换,格式为 '$1':'$2',即可快速提取 Cookie 和其他字段的值。
    • 在浏览器开发者工具中,保留之前抓到的数据包,启用“Preserve log”功能以便于后续分析。

    开发者工具中的搜索功能点击图示中的放大镜,可以快速定位特定请求。

    上一篇:ECharts初试
    下一篇:路由器和交换机简单总结(cisco设备)

    发表评论

    最新留言

    路过,博主的博客真漂亮。。
    [***.116.15.85]2025年04月18日 01时14分51秒