美文网首页
使用python爬取网站音乐(二十三)

使用python爬取网站音乐(二十三)

作者: 梦捷者 | 来源:发表于2019-08-02 10:19 被阅读0次

代码示例如下:

import re
import requests
import json

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}


def start_work(name):
    api = 'https://music.taihe.com/search'
    data = {'key': name}
    resp = requests.get(api, params=data, headers=headers)
    resp.encoding = resp.apparent_encoding
    html = resp.text
    return html


def extract_work(html):
    sids = re.findall(r'data-playdata="(.*?)"', html)
    #获取歌曲id
    data = re.findall(r'\d+', sids[0])
    item = {}
    j = 1
    for i in data:

        url = 'https://musicapi.taihe.com/v1/restserver/ting?method=baidu.ting.song.playAAC&format=jsonp&callback=jQuery17204869203719595674_1564707595390&songid=%s&from=web&_=1564707598783'%i
        content1 = requests.get(url, headers=headers)
        content1.encoding = content1.apparent_encoding
        content = content1.text
        # print(content)

        data1 = re.findall(r'\((.*)\);', content)
        data2 = json.loads(data1[0])
        #获取歌曲信息,歌名,MP3文件地址
        song_name = data2['songinfo']['title']
        item['歌曲名字'] = song_name

        song_mp3_url = data2['bitrate']['file_link']
        item['歌曲地址'] = song_mp3_url
        print('这是第%d首歌,歌名为%s的音乐地址为%s'% (j, song_name, song_mp3_url))

        song_author = data2['songinfo']['author']
        item['歌手名字'] = song_author

        with open('sava.json', 'a', encoding='utf-8') as f:
            text = json.dumps(item, ensure_ascii=False)+'\n'
            f.write(text)

        response_song = requests.get(song_mp3_url)
        #数据保存
        with open(r'C:\Users\Lenovo\Desktop\wangzhe\%s.mp3'%song_name, 'wb') as f:
            f.write(response_song.content)

        j += 1


if __name__ == '__main__':
    name = str(input("请输入你要下载的歌曲的歌手名字:"))
    name = name.strip()
    html_content = start_work(name)
    extract_work(html_content)


相关文章

网友评论

      本文标题:使用python爬取网站音乐(二十三)

      本文链接:https://www.haomeiwen.com/subject/csmkdctx.html