爬虫作业2(酷狗音乐)

import requests

from lxmlimport etree

import csv

import re

import json

headers = {

'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3719.400 QQBrowser/10.5.3715.400',

'cookie':'kg_mid=***'

}

def get_info(url, writer):

res = requests.get(url,headers=headers)

html = etree.HTML(res.text)

infos = html.xpath('//div[@class="pc_temp_songlist  pc_rank_songlist_short"]/ul/li')

for infoin infos:

rank1 = info.xpath('span[3]')[0]

rank = rank1.xpath('string(.)').strip()

name = info.xpath('a/text()')[0]

singer = name.split('-')[0]

song = name.split('-')[1]

time = info.xpath('span[5]/span/text()')[0].strip()

url_link = info.xpath('a/@href')[0]

res1 = requests.get(url_link,headers=headers)

for linein res1.text.split('\r'):

if 'jQuery' in line:

print(line)

if 'dataFromSmarty' in line:

hash = re.findall('"hash":"(.*?)",', line, re.S)[0]

album_id = re.findall('"album_id":(.*?)}', line, re.S)[0]

url_index ='https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19106328788476737324_1563785427610&hash={}&album_id={}'.format(

hash, album_id)

res2 = requests.get(url_index,headers=headers)

json_data = json.loads(re.match(".*?({.*}).*", res2.text).group(1))

# pprint.pprint(json_data)

                play_url = json_data['data']['play_url']

print(rank, singer, song, time, play_url)

writer.writerow([rank, singer, song, time, play_url])

if __name__ =='__main__':

f =open('song.csv','w+',encoding='utf-8',newline='')

writer = csv.writer(f)

writer.writerow(['rank','singer','song','time','play_url'])

urls = ['https://www.kugou.com/yy/rank/home/{}-6666.html?from=rank'.format(str(i))for iin range(1,6)]

for urlin urls:

get_info(url, writer)

f.close()

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # 酷狗歌曲榜单TOP500 import requests headers ={ 'User-Agent':'...
    积雪云端阅读 1,540评论 0 0
  • def parse_detail(self, response): # 1.正常页面, 2.503动物页面(a.重...
    戒灵阅读 3,813评论 0 6
  • 脑海一直有个想法,想做一个音乐播放的小程序。奈何还只停留在脑海之中。音乐的数据的来源是个需要考虑的问题。之前用No...
    Evtion阅读 11,295评论 2 6
  • 恶意 天是青黑色的,伴着蒙蒙细雨。路上不见行人,车是一辆接一辆的。但静谧的让人恐慌。 公交车站只陈茗一个人在等车,...
    爱读书的仙女asd阅读 1,703评论 0 0
  • 王献 2019年1月16日 星期三 天气:晴 今日抽牌:圣杯一 牌义如下: 晨间感受:愉快 日间主要事件: 1.做...
    时光醉了阅读 2,732评论 0 0