芒果TV——百变大咖秀爬虫与数据可视化

本期是对芒果TV视频评论的一次爬虫与数据分析,耗时两个晚上,总体来说比较普通,值得注意的一点是时间戳的处理。
在这里插入图片描述

爬虫方面:由于芒果的评论数据是封装在json里面,所以只需要找到json文件,对需要的数据进行提取保存即可。
在这里插入图片描述

  • 视频网址:https://www.mgtv.com/b/44793/11017269.html?fpa=se&lastp=so_result
  • 评论json数据网址:https://comment.mgtv.com/v4/comment/getCommentList?page=1&subjectType=hunantv2014&subjectId=11017269
  • 注:只要替换subjectId的值,即可爬取其他视频的评论

在这里插入图片描述

数据分析方面:涉及到了词云图,条形,折线,饼图,后三者是对评论时间的分析,然而芒果TV的评论时间是以时间戳的形式显示,所以要进行转换,再去统计出现次数。

项目结构:
在这里插入图片描述
一. 爬虫部分:
1.爬虫代码:spiders.py

# coding=gbk
import csv
import os
import sys
import time

import rdata as rdata
import requests
import json
import pandas as pd


# 封装数据的网站
from python_helper.api.src.service.LogHelper import setting

headers = {
        'cookie': 'cna=J7K2Fok5AXECARu7QWn6+cxu; isg=BCcnDiP-NfKV5bF-OctWuXuatl3xrPuOyBVJJfmQLrZn6ESqAX0y3jrhCuj2ANMG; l=eBSmWoPRQeT6Zn3iBO5whurza77O1CAf1sPzaNbMiIncC6BR1AvOCJxQLtyCvptRR8XcGLLB4nU7C5eTae7_7CDmndLHuI50MbkyCef..',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    }
for i in range(1,99):
    #url = f'https://search.damai.cn/searchajax.html?keyword=&cty=&ctl=%E6%BC%94%E5%94%B1%E4%BC%9A&sctl=&tsg=0&st=&et=&order=1&pageSize=30&currPage={i}&tn='
    url = f'https://comment.mgtv.com/v4/comment/getCommentList?page={i}&subjectType=hunantv2014&subjectId=11017269'
    print(url)

    response = requests.get(url, headers=headers)
    json_text = json.loads(response.text)

    # print(json_text.keys())
    for t in range(1, 14):
        rdata1 = json_text['data']['list'][t]['content']
        rdata2 = int(json_text['data']['list'][t]['createTime'])

        # 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
        timeArray = time.localtime(rdata2)
        rdata2 = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        #print(rdata2)

        print(rdata1,rdata2)

        f = open('百变大咖秀.txt', 'a+',encoding="utf-8")
        print(rdata1,file = f)

        f = open('时间.txt', 'a+', encoding="utf-8")
        print(rdata2, file=f)


        f.close()

2.将评论时间的txt文件读入csv文件
CD.py

# coding=gbk
import csv
csvFile = open("data.csv",'w',newline='',encoding='utf-8')
writer = csv.writer(csvFile)
csvRow = []

f = open("时间.txt",'r',encoding='GB2312')
for line in f:
    csvRow = line.split()
    writer.writerow(csvRow)

f.close()
csvFile.close()

在这里插入图片描述
二. 数据分析
1.制作词云图
wc.py

import numpy as np
import jieba
from wordcloud import WordCloud
from matplotlib import pyplot as plt
from PIL import Image

# 上面的包自己安装,不会的就百度

f = open('../Spiders/百变大咖秀.txt', 'r', encoding='utf-8')  # 这是数据源,也就是想生成词云的数据
txt = f.read()  # 读取文件
f.close()  # 关闭文件,其实用with就好,但是懒得改了
# 如果是文章的话,需要用到jieba分词,分完之后也可以自己处理下再生成词云
words = jieba.lcut(txt)
newtxt = ' '.join(words)
img = Image.open(r'wc.jpg')  # 想要搞得形状
img_array = np.array(img)

# 相关配置,里面这个collocations配置可以避免重复
wordcloud = WordCloud(
    background_color="white",
    width=1080,
    height=960,
    font_path="../文悦新青年.otf",
    max_words=150,
    scale=7,#清晰度
    max_font_size=100,
    mask=img_array,
    collocations=False).generate(txt)

plt.imshow(wordcloud)
plt.axis('off')
plt.show()
wordcloud.to_file('../Photo/result.png')

轮廓图:wc.jpg
在这里插入图片描述
词云图:result.png
(注:停用词自己加,这里没有放)
在这里插入图片描述
2.可视化分析

(1)时间数据处理

py.py (统计一天各个时间段内的评论数)

# coding=gbk
import csv

from pyecharts import options as opts
from sympy.combinatorics import Subset
from wordcloud import WordCloud

with open('../Spiders/data.csv') as csvfile:
    reader = csv.reader(csvfile)

    data1 = [str(row[1])[0:2] for row in reader]

    print(data1)
print(type(data1))


#先变成集合得到seq中的所有元素,避免重复遍历
set_seq = set(data1)
rst = []
for item in set_seq:
    rst.append((item,data1.count(item)))  #添加元素及出现个数
rst.sort()
print(type(rst))
print(rst)

with open("time2.csv", "w+", newline='', encoding='utf-8') as f:
    writer = csv.writer(f, delimiter=',')
    for i in rst:                # 对于每一行的,将这一行的每个元素分别写在对应的列中
        writer.writerow(i)

with open('time2.csv') as csvfile:
     reader = csv.reader(csvfile)
     x = [str(row[0]) for row in reader]
     print(x)
with open('time2.csv') as csvfile:
    reader = csv.reader(csvfile)
    y1 = [float(row[1]) for row in reader]
    print(y1)

处理结果(评论时间,评论数)
在这里插入图片描述
py1.py (统计最近评论数)

# coding=gbk
import csv

from pyecharts import options as opts
from sympy.combinatorics import Subset
from wordcloud import WordCloud

with open('../Spiders/data.csv') as csvfile:
    reader = csv.reader(csvfile)

    data1 = [str(row[0]) for row in reader]
    #print(data1)
print(type(data1))


#先变成集合得到seq中的所有元素,避免重复遍历
set_seq = set(data1)
rst = []
for item in set_seq:
    rst.append((item,data1.count(item)))  #添加元素及出现个数
rst.sort()
print(type(rst))
print(rst)



with open("time1.csv", "w+", newline='', encoding='utf-8') as f:
    writer = csv.writer(f, delimiter=',')
    for i in rst:                # 对于每一行的,将这一行的每个元素分别写在对应的列中
        writer.writerow(i)

with open('time1.csv') as csvfile:
     reader = csv.reader(csvfile)
     x = [str(row[0]) for row in reader]
     print(x)
with open('time1.csv') as csvfile:
    reader = csv.reader(csvfile)
    y1 = [float(row[1]) for row in reader]

    print(y1)



处理结果(评论时间,评论数)
在这里插入图片描述
(2)制作最近评论数条形图与折线图
DrawBar.py

# encoding: utf-8
import csv
import pyecharts.options as opts
from pyecharts.charts import Bar
from pyecharts.globals import ThemeType


class DrawBar(object):

    """绘制柱形图类"""
    def __init__(self):
        """创建柱状图实例,并设置宽高和风格"""
        self.bar = Bar(init_opts=opts.InitOpts(width='1500px', height='700px', theme=ThemeType.LIGHT))

    def add_x(self):
        """为图形添加X轴数据"""
        with open('time1.csv') as csvfile:
            reader = csv.reader(csvfile)
            x = [str(row[0]) for row in reader]
            print(x)


        self.bar.add_xaxis(
            xaxis_data=x,

        )

    def add_y(self):
        with open('time1.csv') as csvfile:
            reader = csv.reader(csvfile)
            y1 = [float(row[1]) for row in reader]

            print(y1)



        """为图形添加Y轴数据,可添加多条"""
        self.bar.add_yaxis(  # 第一个Y轴数据
            series_name="评论数",  # Y轴数据名称
            y_axis=y1,  # Y轴数据
            label_opts=opts.LabelOpts(is_show=False),  # 设置标签
            bar_max_width='70px',  # 设置柱子最大宽度
        )


    def set_global(self):
        """设置图形的全局属性"""
        #self.bar(width=2000,height=1000)
        self.bar.set_global_opts(
            title_opts=opts.TitleOpts(  # 设置标题
                title='百变大咖秀近日评论统计',title_textstyle_opts=opts.TextStyleOpts(font_size=35)

            ),
            tooltip_opts=opts.TooltipOpts(  # 提示框配置项(鼠标移到图形上时显示的东西)
                is_show=True,  # 是否显示提示框
                trigger="axis",  # 触发类型(axis坐标轴触发,鼠标移到时会有一条垂直于X轴的实线跟随鼠标移动,并显示提示信息)
                axis_pointer_type="cross"  # 指示器类型(cross将会生成两条分别垂直于X轴和Y轴的虚线,不启用trigger才会显示完全)
            ),
            toolbox_opts=opts.ToolboxOpts(),  # 工具箱配置项(什么都不填默认开启所有工具)

        )

    def draw(self):
        """绘制图形"""

        self.add_x()
        self.add_y()
        self.set_global()
        self.bar.render('../Html/DrawBar.html')  # 将图绘制到 test.html 文件内,可在浏览器打开
    def run(self):
        """执行函数"""
        self.draw()



if __name__ == '__main__':
    app = DrawBar()

app.run()

效果图:DrawBar.html
在这里插入图片描述
在这里插入图片描述
(3)制作每小时评论条形图与折线图
DrawBar2.py

# encoding: utf-8
import csv
import pyecharts.options as opts
from pyecharts.charts import Bar
from pyecharts.globals import ThemeType


class DrawBar(object):

    """绘制柱形图类"""
    def __init__(self):
        """创建柱状图实例,并设置宽高和风格"""
        self.bar = Bar(init_opts=opts.InitOpts(width='1500px', height='700px', theme=ThemeType.MACARONS))

    def add_x(self):
        """为图形添加X轴数据"""
        str_name1 = '点'

        with open('time2.csv') as csvfile:
            reader = csv.reader(csvfile)
            x = [str(row[0] + str_name1) for row in reader]
            print(x)


        self.bar.add_xaxis(
            xaxis_data=x
        )

    def add_y(self):
        with open('time2.csv') as csvfile:
            reader = csv.reader(csvfile)
            y1 = [int(row[1]) for row in reader]

            print(y1)



        """为图形添加Y轴数据,可添加多条"""
        self.bar.add_yaxis(  # 第一个Y轴数据
            series_name="评论数",  # Y轴数据名称
            y_axis=y1,  # Y轴数据
            label_opts=opts.LabelOpts(is_show=False),  # 设置标签
            bar_max_width='50px',  # 设置柱子最大宽度

        )


    def set_global(self):
        """设置图形的全局属性"""
        #self.bar(width=2000,height=1000)
        self.bar.set_global_opts(
            title_opts=opts.TitleOpts(  # 设置标题
                title='百变大咖秀各时间段评论统计',title_textstyle_opts=opts.TextStyleOpts(font_size=35)

            ),
            tooltip_opts=opts.TooltipOpts(  # 提示框配置项(鼠标移到图形上时显示的东西)
                is_show=True,  # 是否显示提示框
                trigger="axis",  # 触发类型(axis坐标轴触发,鼠标移到时会有一条垂直于X轴的实线跟随鼠标移动,并显示提示信息)
                axis_pointer_type="cross"  # 指示器类型(cross将会生成两条分别垂直于X轴和Y轴的虚线,不启用trigger才会显示完全)
            ),
            toolbox_opts=opts.ToolboxOpts(),  # 工具箱配置项(什么都不填默认开启所有工具)

        )

    def draw(self):
        """绘制图形"""

        self.add_x()
        self.add_y()
        self.set_global()
        self.bar.render('../Html/DrawBar2.html')  # 将图绘制到 test.html 文件内,可在浏览器打开
    def run(self):
        """执行函数"""
        self.draw()



if __name__ == '__main__':
    app = DrawBar()

app.run()

效果图:DrawBar2.html
在这里插入图片描述
在这里插入图片描述(4)制作各类饼图

  • pie_pyecharts.py
import csv

from pyecharts import options as opts
from pyecharts.charts import Pie
from random import randint

from pyecharts.globals import ThemeType

with open('time1.csv') as csvfile:
    reader = csv.reader(csvfile)
    x = [str(row[0]) for row in reader]
    print(x)
with open('time1.csv') as csvfile:
    reader = csv.reader(csvfile)
    y1 = [float(row[1]) for row in reader]

    print(y1)



num = y1
lab = x
(
    Pie(init_opts=opts.InitOpts(width='1500px',height='500px',theme=ThemeType.LIGHT))#默认900,600
    .set_global_opts(
        title_opts=opts.TitleOpts(title="百变大咖秀近日评论统计",
                                               title_textstyle_opts=opts.TextStyleOpts(font_size=27)),legend_opts=opts.LegendOpts(

            pos_top="8%",# 图例位置调整
            ),)
    .add(series_name='',center=[400, 300], data_pair=[(j, i) for i, j in zip(num, lab)])#饼图
   #.add(series_name='',center=[750, 300],data_pair=[(j,i) for i,j in zip(num,lab)],radius=['40%','75%'])#环图
    .add(series_name='', center=[1100, 300],data_pair=[(j, i) for i, j in zip(num, lab)], rosetype='radius')#南丁格尔图
).render('../Html/pie_pyecharts.html')


效果图
在这里插入图片描述

  • pie_pyecharts2.py
import csv

from pyecharts import options as opts
from pyecharts.charts import Pie
from random import randint

from pyecharts.globals import ThemeType

str_name1 = '点'

with open('time2.csv') as csvfile:
    reader = csv.reader(csvfile)
    x = [str(row[0]+str_name1) for row in reader]
    print(x)
with open('time2.csv') as csvfile:
    reader = csv.reader(csvfile)
    y1 = [int(row[1]) for row in reader]

    print(y1)



num = y1
lab = x
(
    Pie(init_opts=opts.InitOpts(width='1520px',height='520px',theme=ThemeType.LIGHT,))#默认900,600
     .set_global_opts(
        title_opts=opts.TitleOpts(title="百变大咖秀每小时评论统计"
                                  ,title_textstyle_opts=opts.TextStyleOpts(font_size=27)),
        legend_opts=opts.LegendOpts(

            pos_top="8%",# 图例位置调整
            ),
    )
    .add(series_name='',center=[250, 320], data_pair=[(j, i) for i, j in zip(num, lab)])#饼图
    .add(series_name='',center=[790, 320],data_pair=[(j,i) for i,j in zip(num,lab)],radius=['40%','75%'])#环图
    .add(series_name='', center=[1262, 320],data_pair=[(j, i) for i, j in zip(num, lab)], rosetype='radius')#南丁格尔图
).render('../Html/pie_pyecharts2.html')


效果图
在这里插入图片描述

  • pie_pyecharts3.py
    观看时间区间评论统计
# coding=gbk
import csv

from pyecharts import options as opts
from pyecharts.globals import ThemeType
from sympy.combinatorics import Subset
from wordcloud import WordCloud

with open('../Spiders/data.csv') as csvfile:
    reader = csv.reader(csvfile)

    data2 = [int(row[1].strip('')[0:2]) for row in reader]


    #print(data2)
print(type(data2))

#先变成集合得到seq中的所有元素,避免重复遍历
set_seq = set(data2)
list = []
for item in set_seq:
    list.append((item,data2.count(item)))  #添加元素及出现个数
list.sort()
print(type(list))
#print(list)


with open("time2.csv", "w+", newline='', encoding='utf-8') as f:
    writer = csv.writer(f, delimiter=',')
    for i in list:                # 对于每一行的,将这一行的每个元素分别写在对应的列中
        writer.writerow(i)


n = 4 #分成n组
m = int(len(list)/n)
list2 = []
for i in range(0, len(list), m):
    list2.append(list[i:i+m])

print("凌晨 : ",list2[0])
print("上午 : ",list2[1])
print("下午 : ",list2[2])
print("晚上 : ",list2[3])

with open('time2.csv') as csvfile:
    reader = csv.reader(csvfile)
    y1 = [int(row[1]) for row in reader]

    print(y1)

n =6
groups = [y1[i:i + n] for i in range(0, len(y1), n)]

print(groups)

x=['凌晨','上午','下午','晚上']
y1=[]
for y1 in groups:
    num_sum = 0
    for groups in y1:
        num_sum += groups

print(x)
print(y1)


import csv

from pyecharts import options as opts
from pyecharts.charts import Pie
from random import randint

str_name1 = '点'

num = y1
lab = x
(
    Pie(init_opts=opts.InitOpts(width='1500px',height='500px',theme=ThemeType.LIGHT))#默认900,600
        .set_global_opts(
        title_opts=opts.TitleOpts(title="百变大咖秀观看时间区间评论统计"
                                  , title_textstyle_opts=opts.TextStyleOpts(font_size=40)),
        legend_opts=opts.LegendOpts(

            pos_top="8%",  # 图例位置调整
        ),
    )
    .add(series_name='',center=[260, 300], data_pair=[(j, i) for i, j in zip(num, lab)])#饼图
   .add(series_name='',center=[1230, 300],data_pair=[(j,i) for i,j in zip(num,lab)],radius=['40%','75%'])#环图
    .add(series_name='', center=[750, 300],data_pair=[(j, i) for i, j in zip(num, lab)], rosetype='radius')#南丁格尔图
).render('../Html/pie_pyecharts3.html')

效果图
在这里插入图片描述
如有需要:请关注微信公众号——小小的代码基地,回复:芒果TV百变大咖秀,即可获得源码

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值