练习---爬取QQ音乐多个歌手的歌单,存取到同一个Excel工作簿中不同sheet表格中

import requests
import json
import openpyxl
import os

def save_music(singer):
	url='https://c.y.qq.com/soso/fcgi-bin/client_search_cp'
	path='C:\\Users\\Xpeng\\Desktop\\爬取到的表格\\歌曲.xlsx'
	
	if os.path.exists(path):
		wb=openpyxl.load_workbook(path)
		sheet=wb.active
		sheet=wb.create_sheet()
		sheet.title=singer
	else:
		wb=openpyxl.Workbook()
		sheet=wb.active
		sheet.title=singer

	rows=[]

	for x in range(3):  #我只爬取了三页
		params = {
			'ct': '24',
			'qqmusic_ver': '1298',
			'new_json': '1',
			'remoteplace': 'sizer.yqq.song_next',
			'searchid': '64405487069162918',
			't': '0',
			'aggr': '1',
			'cr': '1',
			'catZhida': '1',
			'lossless': '0',
			'flag_qc': '0',
			'p': str(x + 1),
			'n': '20',
			'w': singer,
			'g_tk': '5381',
			'loginUin': '0',
			'hostUin': '0',
			'format': 'json',
			'inCharset': 'utf8',
			'outCharset': 'utf-8',
			'notice': '0',
			'platform': 'yqq.json',
			'needNewCode': '0'
		}
    
		res=requests.get(url,params=params)
		json=res.json()
		music=json['data']['song']['list']
	
		for m in music:
			row=[]
			row.append(m['name'])
			row.append(m['album']['name'])
			row.append(str(m['interval']) + '秒')
			row.append('https://y.qq.com/n/yqq/song/' + m['file']['media_mid'] + '.html')
			rows.append(row)
	sheet['A1'] ='歌曲名'
	sheet['B1'] ='所属专辑'
	sheet['C1'] ='播放时长'
	sheet['D1'] ='播放链接'
	for r in rows:
		print(r)
		sheet.append(r)
	wb.save(path)


save_music('孙燕姿')
save_music('周杰伦')
save_music('陈奕迅')

 

你可能感兴趣的:(爬虫学习)