基于python的腾讯视频评论图表化

在编写此程序前您需要引用以下库:

import urllib.request
import http.cookiejar
import re
import time
import jieba
import os
import sys
import json
import requests
import pyecharts

第一部分:爬取视频评论

  这个地方的代码其实不怎么样,不过既然是半成品就不用管这么多了。

  第一步是分析地址构成,使用Fiddler抓包可以得到地址,分析后可得结构:

  https://video.coral.qq.com/varticle/+视频编号+/comment/v2?callback=_varticle3889738104commentv2&orinum=10&oriorder=o&pageflag=1&cursor="+最后评论者id+"&scorecursor=0&orirepnum=2&reporder=o&reppageflag=1&source=132&_=155840371506"+序号

  代码如下:

#设置评论起始编号
comid=******
#设置视频编号
vid=********
#构造出评论网址
url="https://video.coral.qq.com/varticle/"+vid+"/comment/v2?callback=_varticle3889738104commentv2&orinum=10&oriorder=o&pageflag=1&cursor="+comid+"&scorecursor=0&orirepnum=2&reporder=o&reppageflag=1&source=132&_=1558403715061"

 

  第二步就是爬虫的套路了,无论什么网站,设置header,cookies这几步总归要写的,代码如下:

headers={"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
         "Accept-Encoding": "utf-8,gb2312",
         "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en,q=0.3",
         "User-Agent":" Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0",
         "Connection":"keep-alive",
         "referer":"qq.com"}
#设置cookie
cjar=http.cookiejar.CookieJar()
opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cjar))
headall=[]
for key,value in headers.items():
    item=(key,value)
    headall.append(item)
opener.addheaders=headall
urllib.request.install_opener(opener)

 

  之后再次加载评论,得到新的地址,我们可以发现是视频地址是以第一个评论的评论者的ID为标记的,所以我们需要在遍历完所有ID后选择最后一个构造新地址。爬取内容代码如下:

def craw(vid,comid,i):
    url="https://video.coral.qq.com/varticle/"+vid+"/comment/v2?callback=_varticle3889738104commentv2&orinum=10&oriorder=o&pageflag=1&cursor="+comid+"&scorecursor=0&orirepnum=2&reporder=o&reppageflag=1&source=132&_=155840371506"+str(i)
    data=urllib.request.urlopen(url).read().decode('utf-8')
    return data
#构建正则表达式
idpat='"id":"(.*?)"'
conpat='"content":"(.*?)"'
file=open("G://python project/web crawler/pinglun.txt","w+",encoding='utf-8',errors='ignore')
for i in range(1,11):
    print("开始爬取第"+str(i)+"")
    print(""+str(i)+"")
    data=craw(vid,comid,i)
    for j in range(0,10):
        #分别构建筛选id,用户名、评论内容等信息
        idlist=re.compile(idpat,re.S).findall(data)
        conlist=re.compile(conpat,re.S).findall(data)
        file.writelines(conlist[j]+'\n')
        print("评论内容是:"+eval('u"'+conlist[j]+'"'))
        print("\n")
    #设置最后评论者id
    comid=idlist[9]
    print(""+str(i)+"页完成,休眠1秒")
    time.sleep(1)
#将utf-8转换为gbk
newfile=open("G://python project/web crawler/pingluns.txt","w+",encoding='gbk',errors='ignore')
file.seek(0)
all_text=file.read()
newfile.write(all_text)
file.close()
newfile.close()

第二部分:好中差评统计

  因为腾讯视频下的评论没有打星功能,并且我还没有分析情感倾向的库,所以这边偷懒直接用了百度的api,申请开发者可以白嫖,代码如下:

 

# 定义常量,请用自己申请的AI接口
API_KEY = *******
SECRET_KEY = *******
#生成token
COMMENT_TAG_URL = "https://aip.baidubce.com/rpc/2.0/nlp/v2/comment_tag"
TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'
#情感倾向分析
Positive=0
neutral=0
negative=0
def getEmotion(inputText,access_token):
    url='https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?access_token=' + access_token
    header={'Content-Type':'application/json'}
    body={'text':inputText}
    #关闭安全请求警告
    requests.packages.urllib3.disable_warnings()
    res=requests.post(url=url,data=json.dumps(body),headers=header,verify=False)
    if res.status_code==200:
        info=json.loads(res.text)
        global Positive
        global neutral
        global negative
        if 'items' in info and len(info['items'])>0:
            sentiment=info['items'][0]['sentiment']
            if sentiment==2:
               Positive+=1
            elif sentiment==1:
               neutral+=1
            else:
                negative+=1
#获取token
def getToken():
    host='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+API_KEY + '&client_secret=' + SECRET_KEY
    response = requests.get(host)
    if response.status_code==200:
        info=json.loads(response.text)#将字符串转换为字典
        access_token=info['access_token']
        return access_token
    return ''

file=open('G://python project/web crawler/pingluns.txt','r')
accessToken = getToken()
Z=0
for i in file.readlines():
    Z+=1
    print('正在分析第'+str(Z)+"")
    getEmotion(i, accessToken)
    #防止超出请求速度限制
    time.sleep(0.5)
file.close()

 

第三部分:生成可视化视图

  本部分也分为两部分,首先使用jieba库统计关键字,这里我使用了一些网上的停词表,之后根据自己的多次运行结果也写了一些停用词,代码如下:

 

#设置停用词
stopwords01 = [line.strip() for line in open('G://python project/web crawler/stopwords-master/cn_stopwords.txt', 'r',encoding='utf-8').readlines()]
stopwords02 = [line.strip() for line in open('G://python project/web crawler/stopwords-master/hit_stopwords.txt', 'r',encoding='utf-8').readlines()]
stopwords03 = [line.strip() for line in open('G://python project/web crawler/stopwords-master/scu_stopwords.txt', 'r',encoding='utf-8').readlines()]
stopwords04 = [line.strip() for line in open('G://python project/web crawler/stopwords-master/baidu_stopwords.txt', 'r',encoding='utf-8').readlines()]
stopwords05 = [line.strip() for line in open('G://python project/web crawler/stopwords-master/my_stopwords.txt', 'r',encoding='utf-8').readlines()]

txt = open("G://python project/web crawler/pingluns.txt", "r", encoding='GBK').read()
# 使用精确模式对文本进行分词
words = jieba.lcut(txt,cut_all=True)     
counts = {}

for word in words:
    # 单个字和停用词表内的词不会被统计
    if word not in stopwords01 and word not in stopwords02 and word not in stopwords03 and word not in stopwords04 and word not in stopwords05 and len(word) != 1:
            # 遍历所有词语,每出现一次其对应的值加 1
            counts[word] = counts.get(word, 0) + 1
    else:
        continue
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)    
wordlist=[]
countlist=[]
#取出现次数最多的十个词
for i in range(10):
    word, count = items[i]
    wordlist.append(word)
    countlist.append(count)
    print(word,count)

 

  第二部分就是使用pycharts库建立可视化图表(html格式)。这部分代码也比较简单,我是用的是老版代码,因为新版的不是很会用哈哈。代码如下:

attr = wordlist
v1 = countlist
page = pyecharts.Page()
bar = pyecharts.Bar('热词统计','前十热词')
pie = pyecharts.Pie('观看体验','占比划分')
bar.add("", attr, v1, is_label_show=True)
page.add_chart(bar)
pie.add("", ['好评','中评','差评'], [Positive,neutral,negative],is_label_show=True)
page.add_chart(pie)
page.render()
os.system("render.html")

这就是这个程序的答题思路和代码,还有很多不如意的地方,比如没有办法实现自己加载第一条评论的评论者的ID等等,如果各位的时间足够的话可以自己尝试优化一下。

 

posted @ 2021-02-25 22:42  咸鱼划水  阅读(85)  评论(0编辑  收藏  举报