├── README.md └── B站弹幕、评论爬虫.py /README.md: -------------------------------------------------------------------------------- 1 | # B站弹幕、评论爬虫+词云生成 2 | # 使用方法 3 | 先获取B站视频链接,如不知道格式,可以先运行 本项目中的 py文件,然后按照提示即可获取。 4 | 获取链接之后,启动 py文件 ,按照提示输入即可 5 | -------------------------------------------------------------------------------- /B站弹幕、评论爬虫.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import re 3 | import jieba 4 | import wordcloud 5 | import time 6 | import sys 7 | from bs4 import BeautifulSoup 8 | class Bilibili: 9 | def __init__(self, videourl,page,img_path): 10 | 11 | self.img_path=img_path 12 | self.baseurl=videourl.split('?')[0] 13 | # 爬取弹幕和评论 14 | def getAidAndCid(self): 15 | cidurl=self.baseurl+"?p="+page 16 | cidRegx='{"cid":([\d]+),"page":%s,'%(page) 17 | aidRegx='"aid":([\d]+),' 18 | r=requests.get(cidurl) 19 | r.encoding='utf-8' 20 | try: 21 | 22 | self.cid=re.findall(cidRegx, r.text)[0] 23 | self.aid=re.findall(aidRegx, r.text)[int(page)-1] 24 | except: 25 | print('视频序号输入有误,请保证序号在1到最大值之间!') 26 | time.sleep(3) 27 | sys.exit() 28 | 29 | 30 | def getBarrage(self): 31 | print('正在获取弹幕......') 32 | 33 | commentUrl='https://comment.bilibili.com/'+self.cid+'.xml' 34 | 35 | # 获取并提取弹幕 # 36 | r=requests.get(commentUrl) 37 | r.encoding='utf-8' 38 | content=r.text 39 | # 正则表达式匹配字幕文本 40 | comment_list=re.findall('>(.*?)0: 79 | print('------视频列表------') 80 | for i in result: 81 | count+=1 82 | print("视频"+str(count)+" : "+i) 83 | return 1 84 | return 0 85 | 86 | if __name__=='__main__': 87 | # 视频地址 88 | videourl=input("请输入视频地址,例如:https://www.bilibili.com/video/BV13x41147nB\n") 89 | 90 | if checkUrl(videourl): 91 | print('------视频地址有效------') 92 | 93 | # 第n个视频 94 | page=input('请输入视频的序号:') 95 | 96 | # 图片储存路径 97 | img_path=input('请输入你要生成的词云的图片名称:') 98 | 99 | # 计时 100 | start_time=time.time() 101 | 102 | # 实例化类 103 | b=Bilibili(videourl, page, img_path) 104 | 105 | # 获取aid和cid 106 | b.getAidAndCid() 107 | 108 | # 获取弹幕 109 | b.getBarrage() 110 | 111 | # 获取评论 起始页和结束页 112 | # b.getComment(1, 4) 113 | 114 | # 生成词云 115 | b.genWordCloud() 116 | 117 | print('程序运行完毕,耗时:{:.2f}s'.format(time.time()-start_time)) 118 | else: 119 | print('视频地址无效') 120 | 121 | 122 | 123 | 124 | 125 | --------------------------------------------------------------------------------