实战演练爬取网易云音乐的评价

本文介绍如何实战爬取网易云音乐的评论,涉及的知识点包括jsonpath用于解析json内容,pandas进行数据处理,以及time模块进行时间操作。提供了相关学习资源链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实战爬取网易云评价(2020年2月25日17:40:25)


一、首先要了解一下网易云的一些接口api
这里传送门:https://blog.youkuaiyun.com/hackerfei1212/article/details/104500895
二、知识点
1. jsonpath的使用寻找json里的内容
 jsonpath.jsonpath(job,'$..content')[0] #$表示从头匹配..表示依次寻找
2. pandas的使用

Pandas 数据框类是一个表(Table)类的数据结构:
首行是栏目 (Column),最左侧是行数 (Row Number),也可以叫索引 (Index)
https://zhuanlan.zhihu.com/p/88632689学习网址

pd.DataFrame(data) #创建 
df = pd.DataFrame(columns=['A', 'B', 'C'], index=['id 1', 'id 2', 'id 3'])#创建一个
3. time的使用

将时间格式化 https://www.runoob.com/python/python-date-time.html学习网址

time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(str(stamp)[0:10])))
三、上代码
# -*- coding: utf-8 -*-
"""
Created on 2020年2月25日16:51:11
@author: Arthur
"""
import requests
import jsonpath
import pandas as pd
import time

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

def get_json(url):
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            json_text=response.json()
            return json_text
    except Exception:
        print('此页有问题!')
        return None
    
def stampToTime(stamp): #时间转换
    datatime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(str(stamp)[0:10])))
    datatime = datatime+'.'+str(stamp)[10:]
    return datatime

def get_comments(url):
    data = []
    doc = get_json(url)
    jobs=doc['hotComments']
    for job in jobs:
        dic = {}
        #从根节点开始,匹配content节点
        dic['content']=jsonpath.jsonpath(job,'$..content')[0] #评论
        dic['time']= stampToTime(jsonpath.jsonpath(job,'$..time')[0]) #时间
        dic['userId']=jsonpath.jsonpath(job['user'],'$..userId')[0]  #用户ID
        dic['nickname']=jsonpath.jsonpath(job['user'],'$..nickname')[0]#用户名
        dic['likedCount']=jsonpath.jsonpath(job,'$..likedCount')[0] #赞数
        data.append(dic)
    return pd.DataFrame(data)

final_result = get_comments('http://music.163.com/api/v1/resource/comments/R_SO_4_483671599?limit=10&offset=0')
final_result.to_csv('1.csv')   #导出csv文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值