题目:打印出网易云搜索结果结果中所有的歌名,id和歌手图片
代码如下:

#! /usr/bin/python3
import requests,json

userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
url = "http://music.163.com/api/search/pc"
header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Host': 'music.163.com',
        'Referer': 'http://music.163.com/',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': userAgent
        }

def search_songs(singerName):
    data = {
    "s" : singerName,
    "offset" : 10,
    "total" : True,
    "limit" : 100,
    "type" : 1
    }
    r = requests.post(url,headers=header,data=data)
    res= json.loads(r.text)
    return res

result = search_songs("陈奕迅")
#print(result)

"""
提示!!!:本题难度高,需要熟练掌握list,dict,循环的应用。可选做
-----------------------------------------
运行前,请在cmd中执行:pip install requests
-----------------------------------------

运行以上代码,可以爬取网易云的搜索结果,并把结果转化为dict形式赋值给了变量result。
请使用循环和判断,打印出结果中所有的歌名,id和歌手图片(分别对应:name,id,artists中的picUrl)
"""
resultlist=list(result.values())
songdict=resultlist[0]
songlist=songdict['songs']
num=len(songlist)
for i in range(num):
    name=songlist[i]['name']
    id=songlist[i]['id']
    picUrl=songlist[i]['artists'][0]['picUrl']
    print('-'*90)
    print('歌名:',name)
    print('ID:',id)
    print('歌手图片:',picUrl)
Last modification:February 18th, 2019 at 02:40 pm
If you think my article is useful to you, please feel free to appreciate