本期是对热播网剧《雪中悍刀行》的一次爬虫与数据分析,总爬取条数1W条评论,很适合新人练手。案例中还特别加入了对评论的情绪文本分析处理,供大家参考。 爬虫方面:由于腾讯的评论数据是封装在json里面,所以只需要找到json文件,对需要的数据进行提取保存即可。 私信小编01即可获取大量Python学习资源 视频网址: https:v。qq。comxcovermzc0020020cyvqh。html 评论json数据网址: https:video。coral。qq。comvarticle7579013546commentv2 注:只要替换视频数字id的值,即可爬取其他视频的评论 本文内容仅作为编程技术学习讨论,相关代码和数据不可用于商业用途,否则后果自负。如何查找视频id? 通过Chrome开发者工具的Network查找请求。具体使用可参考旧文:爬虫必备工具,掌握它就解决了一半的问题项目结构: 一。爬虫部分:1。爬取评论内容代码:spiders。pyimportrequestsimportreimportrandomdefgethtml(url,params):uapools〔Mozilla5。0(MIntelMacOSX1092)AppleWebKit537。36(KHTML,likeGecko)Chrome35。0。1916。153Safari537。36,Mozilla5。0(WindowsNT6。1;WOW64;rv:30。0)Gecko20100101Firefox30。0,Mozilla5。0(MIntelMacOSX1092)AppleWebKit537。75。14(KHTML,likeGecko)Version7。0。3Safari537。75。14〕thisuarandom。choice(uapools)headers{UserAgent:thisua}rrequests。get(url,headersheaders,paramsparams)r。raiseforstatus()r。encodingr。apparentencodingr。encodingutf8不加此句出现乱码returnr。textdefparsepage(infolist,data):commentpatcontent:(。?)lastpatlast:(。?)commentallre。compile(commentpat,re。S)。findall(data)nextcidre。compile(lastpat)。findall(data)〔0〕infolist。append(commentall)returnnextciddefprintcommentlist(infolist):j0forpageininfolist:print(第str(j1)页)commentallpageforiinrange(0,len(commentall)):print(commentall〔i〕)j1defsavetotxt(infolist,path):fwopen(path,w,encodingutf8)j0forpageininfolist:fw。write(第str(j1)页)commentallpageforiinrange(0,len(commentall)):fw。write(commentall〔i〕)j1fw。close()defmain():infolist〔〕vid7579013546;cid0;pagenum3000urlhttps:video。coral。qq。comvarticlevidcommentv2print(url)foriinrange(pagenum):params{orinum:10,cursor:cid}htmlgethtml(url,params)cidparsepage(infolist,html)printcommentlist(infolist)savetotxt(infolist,content。txt)main()2。爬取评论时间代码sp。pyimportrequestsimportreimportrandomdefgethtml(url,params):uapools〔Mozilla5。0(MIntelMacOSX1092)AppleWebKit537。36(KHTML,likeGecko)Chrome35。0。1916。153Safari537。36,Mozilla5。0(WindowsNT6。1;WOW64;rv:30。0)Gecko20100101Firefox30。0,Mozilla5。0(MIntelMacOSX1092)AppleWebKit537。75。14(KHTML,likeGecko)Version7。0。3Safari537。75。14〕thisuarandom。choice(uapools)headers{UserAgent:thisua}rrequests。get(url,headersheaders,paramsparams)r。raiseforstatus()r。encodingr。apparentencodingr。encodingutf8不加此句出现乱码returnr。textdefparsepage(infolist,data):commentpattime:(。?)lastpatlast:(。?)commentallre。compile(commentpat,re。S)。findall(data)nextcidre。compile(lastpat)。findall(data)〔0〕infolist。append(commentall)returnnextciddefprintcommentlist(infolist):j0forpageininfolist:print(第str(j1)页)commentallpageforiinrange(0,len(commentall)):print(commentall〔i〕)j1defsavetotxt(infolist,path):fwopen(path,w,encodingutf8)j0forpageininfolist:fw。write(第str(j1)页)commentallpageforiinrange(0,len(commentall)):fw。write(commentall〔i〕)j1fw。close()defmain():infolist〔〕vid7579013546;cid0;pagenum3000urlhttps:video。coral。qq。comvarticlevidcommentv2print(url)foriinrange(pagenum):params{orinum:10,cursor:cid}htmlgethtml(url,params)cidparsepage(infolist,html)printcommentlist(infolist)savetotxt(infolist,time。txt)main()二。数据处理部分1。评论的时间戳转换为正常时间time。pycodinggbkimportcsvimporttimecsvFileopen(data。csv,w,newline,encodingutf8)writercsv。writer(csvFile)csvRow〔〕print(csvRow)fopen(time。txt,r,encodingutf8)forlineinf:csvRowint(line)print(csvRow)timeArraytime。localtime(csvRow)csvRowtime。strftime(YmdH:M:S,timeArray)print(csvRow)csvRowcsvRow。split()writer。writerow(csvRow)f。close()csvFile。close()2。评论内容读入csvCD。pycodinggbkimportcsvcsvFileopen(content。csv,w,newline,encodingutf8)writercsv。writer(csvFile)csvRow〔〕fopen(content。txt,r,encodingutf8)forlineinf:csvRowline。split()writer。writerow(csvRow)f。close()csvFile。close()3。统计一天各个时间段内的评论数py。pycodinggbkimportcsvfrompyechartsimportoptionsasoptsfromsympy。combinatoricsimportSubsetfromwordcloudimportWordCloudwithopen(。。Spidersdata。csv)ascsvfile:readercsv。reader(csvfile)data1〔str(row〔1〕)〔0:2〕forrowinreader〕print(data1)print(type(data1))先变成集合得到seq中的所有元素,避免重复遍历setseqset(data1)rst〔〕foriteminsetseq:rst。append((item,data1。count(item)))添加元素及出现个数rst。sort()print(type(rst))print(rst)withopen(time2。csv,w,newline,encodingutf8)asf:writercsv。writer(f,delimiter,)foriinrst:对于每一行的,将这一行的每个元素分别写在对应的列中writer。writerow(i)withopen(time2。csv)ascsvfile:readercsv。reader(csvfile)x〔str(row〔0〕)forrowinreader〕print(x)withopen(time2。csv)ascsvfile:readercsv。reader(csvfile)y1〔float(row〔1〕)forrowinreader〕print(y1)4。统计最近评论数py1。pycodinggbkimportcsvfrompyechartsimportoptionsasoptsfromsympy。combinatoricsimportSubsetfromwordcloudimportWordCloudwithopen(。。Spidersdata。csv)ascsvfile:readercsv。reader(csvfile)data1〔str(row〔0〕)forrowinreader〕print(data1)print(type(data1))先变成集合得到seq中的所有元素,避免重复遍历setseqset(data1)rst〔〕foriteminsetseq:rst。append((item,data1。count(item)))添加元素及出现个数rst。sort()print(type(rst))print(rst)withopen(time1。csv,w,newline,encodingutf8)asf:writercsv。writer(f,delimiter,)foriinrst:对于每一行的,将这一行的每个元素分别写在对应的列中writer。writerow(i)withopen(time1。csv)ascsvfile:readercsv。reader(csvfile)x〔str(row〔0〕)forrowinreader〕print(x)withopen(time1。csv)ascsvfile:readercsv。reader(csvfile)y1〔float(row〔1〕)forrowinreader〕print(y1) 三。数据分析 数据分析方面:涉及到了词云图,条形,折线,饼图,后三者是对评论时间与主演占比的分析,然而腾讯的评论时间是以时间戳的形式显示,所以要进行转换,再去统计出现次数,最后,新加了对评论内容的情感分析。1。制作词云图 wc。pyimportnumpyasnpimportreimportjiebafromwordcloudimportWordCloudfrommatplotlibimportpyplotaspltfromPILimportImage上面的包自己安装,不会的就百度fopen(content。txt,r,encodingutf8)这是数据源,也就是想生成词云的数据txtf。read()读取文件f。close()关闭文件,其实用with就好,但是懒得改了如果是文章的话,需要用到jieba分词,分完之后也可以自己处理下再生成词云newtxtre。sub(〔AZaz09!〔〕,。〕,,txt)print(newtxt)wordsjieba。lcut(newtxt)imgImage。open(rwc。jpg)想要搞得形状imgarraynp。array(img)相关配置,里面这个collocations配置可以避免重复wordcloudWordCloud(backgroundcolorwhite,width1080,height960,fontpath。。文悦新青年。otf,maxwords150,scale10,清晰度maxfontsize100,maskimgarray,collocationsFalse)。generate(newtxt)plt。imshow(wordcloud)plt。axis(off)plt。show()wordcloud。tofile(wc。png) 轮廓图:wc。jpg 词云图:result。png(注:这里把英文字母过滤掉) 2。制作最近评论数条形图 DrawBar。pyencoding:utf8importcsvimportpyecharts。optionsasoptsfrompyecharts。chartsimportBarfrompyecharts。globalsimportThemeTypeclassDrawBar(object):绘制柱形图类definit(self):创建柱状图实例,并设置宽高和风格self。barBar(initoptsopts。InitOpts(width1500px,height700px,themeThemeType。LIGHT))defaddx(self):为图形添加X轴数据withopen(time1。csv)ascsvfile:readercsv。reader(csvfile)x〔str(row〔0〕)forrowinreader〕print(x)self。bar。addxaxis(xaxisdatax,)defaddy(self):withopen(time1。csv)ascsvfile:readercsv。reader(csvfile)y1〔float(row〔1〕)forrowinreader〕print(y1)为图形添加Y轴数据,可添加多条self。bar。addyaxis(第一个Y轴数据seriesname评论数,Y轴数据名称yaxisy1,Y轴数据labeloptsopts。LabelOpts(isshowTrue,colorblack),设置标签barmaxwidth100px,设置柱子最大宽度)defsetglobal(self):设置图形的全局属性self。bar(width2000,height1000)self。bar。setglobalopts(titleoptsopts。TitleOpts(设置标题title雪中悍刀行近日评论统计,titletextstyleoptsopts。TextStyleOpts(fontsize35)),tooltipoptsopts。TooltipOpts(提示框配置项(鼠标移到图形上时显示的东西)isshowTrue,是否显示提示框triggeraxis,触发类型(axis坐标轴触发,鼠标移到时会有一条垂直于X轴的实线跟随鼠标移动,并显示提示信息)axispointertypecross指示器类型(cross将会生成两条分别垂直于X轴和Y轴的虚线,不启用trigger才会显示完全)),toolboxoptsopts。ToolboxOpts(),工具箱配置项(什么都不填默认开启所有工具))defdraw(self):绘制图形self。addx()self。addy()self。setglobal()self。bar。render(。。HtmlDrawBar。html)将图绘制到test。html文件内,可在浏览器打开defrun(self):执行函数self。draw()ifnamemain:appDrawBar()app。run() 效果图:DrawBar。html 3。制作每小时评论条形图 DrawBar2。pyencoding:utf8encoding:utf8importcsvimportpyecharts。optionsasoptsfrompyecharts。chartsimportBarfrompyecharts。globalsimportThemeTypeclassDrawBar(object):绘制柱形图类definit(self):创建柱状图实例,并设置宽高和风格self。barBar(initoptsopts。InitOpts(width1500px,height700px,themeThemeType。MACARONS))defaddx(self):为图形添加X轴数据strname1点withopen(time2。csv)ascsvfile:readercsv。reader(csvfile)x〔str(row〔0〕strname1)forrowinreader〕print(x)self。bar。addxaxis(xaxisdatax)defaddy(self):withopen(time2。csv)ascsvfile:readercsv。reader(csvfile)y1〔int(row〔1〕)forrowinreader〕print(y1)为图形添加Y轴数据,可添加多条self。bar。addyaxis(第一个Y轴数据seriesname评论数,Y轴数据名称yaxisy1,Y轴数据labeloptsopts。LabelOpts(isshowFalse),设置标签barmaxwidth50px,设置柱子最大宽度)defsetglobal(self):设置图形的全局属性self。bar(width2000,height1000)self。bar。setglobalopts(titleoptsopts。TitleOpts(设置标题title雪中悍刀行各时间段评论统计,titletextstyleoptsopts。TextStyleOpts(fontsize35)),tooltipoptsopts。TooltipOpts(提示框配置项(鼠标移到图形上时显示的东西)isshowTrue,是否显示提示框triggeraxis,触发类型(axis坐标轴触发,鼠标移到时会有一条垂直于X轴的实线跟随鼠标移动,并显示提示信息)axispointertypecross指示器类型(cross将会生成两条分别垂直于X轴和Y轴的虚线,不启用trigger才会显示完全)),toolboxoptsopts。ToolboxOpts(),工具箱配置项(什么都不填默认开启所有工具))defdraw(self):绘制图形self。addx()self。addy()self。setglobal()self。bar。render(。。HtmlDrawBar2。html)将图绘制到test。html文件内,可在浏览器打开defrun(self):执行函数self。draw()ifnamemain:appDrawBar()app。run() 效果图:DrawBar2。html 4。制作近日评论数饼图piepyecharts。py importcsvfrompyechartsimportoptionsasoptsfrompyecharts。chartsimportPiefromrandomimportrandintfrompyecharts。globalsimportThemeTypewithopen(time1。csv)ascsvfile:readercsv。reader(csvfile)x〔str(row〔0〕)forrowinreader〕print(x)withopen(time1。csv)ascsvfile:readercsv。reader(csvfile)y1〔float(row〔1〕)forrowinreader〕print(y1)numy1labx(Pie(initoptsopts。InitOpts(width1700px,height450px,themeThemeType。LIGHT))默认900,600。setglobalopts(titleoptsopts。TitleOpts(title雪中悍刀行近日评论统计,titletextstyleoptsopts。TextStyleOpts(fontsize27)),legendoptsopts。LegendOpts(postop10,posleft1,图例位置调整),)。add(seriesname,center〔280,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕)饼图。add(seriesname,center〔845,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕,radius〔40,75〕)环图。add(seriesname,center〔1380,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕,rosetyperadius)南丁格尔图)。render(piepyecharts。html) 效果图 5。制作每小时评论饼图 piepyecharts2。pyimportcsvfrompyechartsimportoptionsasoptsfrompyecharts。chartsimportPiefromrandomimportrandintfrompyecharts。globalsimportThemeTypestrname1点withopen(time2。csv)ascsvfile:readercsv。reader(csvfile)x〔str(row〔0〕strname1)forrowinreader〕print(x)withopen(time2。csv)ascsvfile:readercsv。reader(csvfile)y1〔int(row〔1〕)forrowinreader〕print(y1)numy1labx(Pie(initoptsopts。InitOpts(width1650px,height500px,themeThemeType。LIGHT,))默认900,600。setglobalopts(titleoptsopts。TitleOpts(title雪中悍刀行每小时评论统计,titletextstyleoptsopts。TextStyleOpts(fontsize27)),legendoptsopts。LegendOpts(postop8,posleft4,图例位置调整),)。add(seriesname,center〔250,300〕,datapair〔(j,i)fori,jinzip(num,lab)〕)饼图。add(seriesname,center〔810,300〕,datapair〔(j,i)fori,jinzip(num,lab)〕,radius〔40,75〕)环图。add(seriesname,center〔1350,300〕,datapair〔(j,i)fori,jinzip(num,lab)〕,rosetyperadius)南丁格尔图)。render(piepyecharts2。html) 效果图 6。制作观看时间区间评论统计饼图 piepyecharts3。pycodinggbkimportcsvfrompyechartsimportoptionsasoptsfrompyecharts。globalsimportThemeTypefromsympy。combinatoricsimportSubsetfromwordcloudimportWordCloudfrompyecharts。chartsimportPiefromrandomimportrandintwithopen(data。csv)ascsvfile:readercsv。reader(csvfile)data2〔int(row〔1〕。strip()〔0:2〕)forrowinreader〕print(data2)print(type(data2))先变成集合得到seq中的所有元素,避免重复遍历setseqset(data2)list〔〕foriteminsetseq:list。append((item,data2。count(item)))添加元素及出现个数list。sort()print(type(list))print(list)withopen(time2。csv,w,newline,encodingutf8)asf:writercsv。writer(f,delimiter,)foriinlist:对于每一行的,将这一行的每个元素分别写在对应的列中writer。writerow(i)n4分成n组mint(len(list)n)list2〔〕foriinrange(0,len(list),m):list2。append(list〔i:im〕)print(凌晨:,list2〔0〕)print(上午:,list2〔1〕)print(下午:,list2〔2〕)print(晚上:,list2〔3〕)withopen(time2。csv)ascsvfile:readercsv。reader(csvfile)y1〔int(row〔1〕)forrowinreader〕print(y1)n6groups〔y1〔i:in〕foriinrange(0,len(y1),n)〕print(groups)x〔凌晨,上午,下午,晚上〕y1〔〕fory1ingroups:numsum0forgroupsiny1:numsumgroupsstrname1点numy1labx(Pie(initoptsopts。InitOpts(width1500px,height450px,themeThemeType。LIGHT))默认900,600。setglobalopts(titleoptsopts。TitleOpts(title雪中悍刀行观看时间区间评论统计,titletextstyleoptsopts。TextStyleOpts(fontsize30)),legendoptsopts。LegendOpts(postop8,图例位置调整),)。add(seriesname,center〔260,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕)饼图。add(seriesname,center〔1230,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕,radius〔40,75〕)环图。add(seriesname,center〔750,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕,rosetyperadius)南丁格尔图)。render(piepyecharts3。html) 效果图 7。制作雪中悍刀行主演提及占比饼图 piepyecharts4。py importcsv frompyechartsimportoptionsasopts frompyecharts。chartsimportPie fromrandomimportrandint frompyecharts。globalsimportThemeType fopen(content。txt,r,encodingutf8)这是数据源,也就是想生成词云的数据 wordsf。read()读取文件 f。close()关闭文件,其实用with就好,但是懒得改了 name〔张若昀,李庚希,胡军〕 print(name) count〔float(words。count(张若昀)), float(words。count(李庚希)), float(words。count(胡军))〕 print(count) numcount labname ( Pie(initoptsopts。InitOpts(width1650px,height450px,themeThemeType。LIGHT))默认900,600 。setglobalopts( titleoptsopts。TitleOpts(title雪中悍刀行主演提及占比, titletextstyleoptsopts。TextStyleOpts(fontsize27)),legendoptsopts。LegendOpts( postop3,posleft33,图例位置调整 ),) 。add(seriesname,center〔280,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕)饼图 。add(seriesname,center〔800,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕,radius〔40,75〕)环图 。add(seriesname,center〔1300,270〕,datapair〔(j,i)fori,jinzip(num,lab)〕,rosetyperadius)南丁格尔图 )。render(piepyecharts4。html) 效果图 8。评论内容情感分析 SnowNLP。py importnumpyasnp fromsnownlpimportSnowNLP importmatplotlib。pyplotasplt fopen(content。txt,r,encodingUTF8) listf。readlines() sentimentslist〔〕 foriinlist: sSnowNLP(i) print(s。sentiments) sentimentslist。append(s。sentiments) plt。hist(sentimentslist,binsnp。arange(0,1,0。01),facecolorg) plt。xlabel(SentimentsProbability) plt。ylabel(Quantity) plt。title(AnalysisofSentiments) plt。show()效果图(情感各分数段出现频率) SnowNLP情感分析是基于情感词典实现的,其简单的将文本分为两类,积极和消极,返回值为情绪的概率,也就是情感评分在〔0,1〕之间,越接近1,情感表现越积极,越接近0,情感表现越消极。总结 以上就是如何获取腾讯视频评论并整理后进行可视化分析,属于数据分析及可视化的常规操作,没有特别高深的技术,还比较适合数据分析初学者练习,读者可以自行动手尝试。全部代码已在文中给出。