一 . Java爬取B站弹幕

弹幕的存储位置

如何通过B站视频AV号找到弹幕对应的xml文件号

首先爬取视频网页,将对应视频网页源码获得

就可以找到该视频的av号aid=8678034

还有弹幕序号,cid=14295428

弹幕存放位置为  http://comment.bilibili.com/14295428.xml

 import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class getBiliBiliBofqi {
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
public static void getBofqi(String aid) throws Exception {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://www.bilibili.com/video/av" + aid + "/");
CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String en = EntityUtils.toString(httpEntity);
//"cid=16496518&aid=9979006&pre_ad="
String con = "cid=(.*)?&aid=";
Pattern ah = Pattern.compile(con);
Matcher mr = ah.matcher(en);
while (mr.find()) {
String id = mr.group();
// 解析弹幕xml文件
String newUrl = id.replace("cid=", "");
String x = newUrl.replace("&aid=", "");
if(!isInteger(x)){
return ;
}
URL url = new URL( "http://comment.bilibili.com/"+x+".xml" );
HttpGet httpGet1 = new HttpGet("http://comment.bilibili.com/"+x+".xml");
CloseableHttpResponse httpResponse1 = closeableHttpClient.execute(httpGet1) ;
HttpEntity httpEntity1 = httpResponse1.getEntity() ;
String en1 = EntityUtils.toString(httpEntity1,"utf-8") ; String c = "\">(.*?)<";
Pattern a = Pattern.compile(c);
Matcher m = a.matcher(en1);
RandomAccessFile randomAccessFile = new RandomAccessFile("E:\\dan_"+x+".txt", "rw");
while (m.find()) {
String speak = m.group().replace("\">", "");
speak = speak.replace("<", ""); // 存储弹幕
long len = randomAccessFile.length();
randomAccessFile.seek(len);
randomAccessFile.write(speak.getBytes());
randomAccessFile.write("\r\n".getBytes());
System.out.println(speak);
}
randomAccessFile.write("\r\n".getBytes());
randomAccessFile.close();
}
}
public static void main(String[] args) throws Exception {
getBofqi("16772795");
getBofqi("8542373");
getBofqi("5112921");
getBofqi("1747345");
getBofqi("2648921");
getBofqi("2333333");
getBofqi("3771373");
getBofqi("17224371");
}
}

爬取的弹幕文件 :

运行结果:

二 . Python云图Wordcloud生成弹幕词云

1      github:https://github.com/amueller/word_cloud
官方地址:https://amueller.github.io/word_cloud/

# coding: utf-8
import jieba
from scipy.misc import imread # 这是一个处理图像的函数
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt back_color = imread('02.jpg') # 解析该图片 wc = WordCloud(background_color='white', # 背景颜色
max_words=500, # 最大词数
#mask=back_color, # 以该参数值作图绘制词云,这个参数不为空时,width和height会被忽略
max_font_size=100, # 显示字体的最大值
stopwords=STOPWORDS.add('fa'), # 使用内置的屏蔽词,再添加'苟利国'
font_path="C:/Windows/Fonts/STFANGSO.ttf", # 解决显示口字型乱码问题,可进入C:/Windows/Fonts/目录更换字体
random_state=42, # 为每个词返回一个PIL颜色
width=1000, # 图片的宽
height=860 #图片的长
)
# WordCloud各含义参数请点击 wordcloud参数 # 打开词源的文本文件
text = open('dan_6051409.txt').read() # 该函数的作用就是把屏蔽词去掉,使用这个函数就不用在WordCloud参数中添加stopwords参数了
# 把你需要屏蔽的词全部放入一个stopwords文本文件里即可
def stop_words(texts):
words_list = []
word_generator = jieba.cut(texts, cut_all=False) # 返回的是一个迭代器
with open('stopwords.txt') as f:
str_text = f.read()
unicode_text = unicode(str_text, 'utf-8') # 把str格式转成unicode格式
f.close() # stopwords文本中词的格式是'一词一行'
for word in word_generator:
if word.strip() not in unicode_text:
words_list.append(word)
return ' '.join(words_list) # 注意是空格 text = stop_words(text) wc.generate(text)
# 基于彩色图像生成相应彩色
image_colors = ImageColorGenerator(back_color)
# 显示图片
plt.imshow(wc)
# 关闭坐标轴
plt.axis('off')
# 绘制词云
plt.figure()
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis('off')
# 保存图片
wc.to_file('1.png')

word_cloud 生成词云有两个方法。from text 和 from frequencies 。

即文本生成和频率生成,每一个都有对应的函数可以使用

 generate(text)      Generate wordcloud from text.
generate_from_text(text) Generate wordcloud from text.
generate_from_frequencies Create a word_cloud from words and frequencies.
fit_words Create a word_cloud from words and frequencies.

wordcloud包的基本用法

 class wordcloud.WordCloud(font_path=None, width=400, height=200, margin=2,
ranks_only=None, prefer_horizontal=0.9,mask=None, scale=1, color_func=None,
max_words=200, min_font_size=4, stopwords=None, random_state=None,background_color='black',
max_font_size=None, font_step=1, mode='RGB', relative_scaling=0.5, regexp=None,
collocations=True,colormap=None, normalize_plurals=True)
  1. font_path : string //字体路径,需要展现什么字体就把该字体路径+后缀名写上,如:font_path = '黑体.ttf'
  2. width : int (default=400) //输出的画布宽度,默认为400像素
  3. height : int (default=200) //输出的画布高度,默认为200像素
  4. prefer_horizontal : float (default=0.90) //词语水平方向排版出现的频率,默认 0.9 (所以词语垂直方向排版出现频率为 0.1 )
  5. mask : nd-array or None (default=None) //如果参数为空,则使用二维遮罩绘制词云。如果 mask 非空,设置的宽高值将被忽略,遮罩形状被 mask 取代。
  6. 除全白(#FFFFFF)的部分将不会绘制,其余部分会用于绘制词云。如:bg_pic = imread('读取一张图片.png'),
  7. 背景图片的画布一定要设置为白色(#FFFFFF),然后显示的形状为不是白色的其他颜色。可以用ps工具将自己要显示的形状复制到一个纯白色的画布上再保存,就ok了。
  8. scale : float (default=1) //按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍。
  9. min_font_size : int (default=4) //显示的最小的字体大小
  10. font_step : int (default=1) //字体步长,如果步长大于1,会加快运算但是可能导致结果出现较大的误差。
  11. max_words : number (default=200) //要显示的词的最大个数
  12. stopwords : set of strings or None //设置需要屏蔽的词,如果为空,则使用内置的STOPWORDS
  13. background_color : color value (default=”black”) //背景颜色,如background_color='white',背景颜色为白色。
  14. max_font_size : int or None (default=None) //显示的最大的字体大小
  15. mode : string (default=”RGB”) //当参数为“RGBA”并且background_color不为空时,背景为透明。
  16. relative_scaling : float (default=.5) //词频和字体大小的关联性
  17. color_func : callable, default=None //生成新颜色的函数,如果为空,则使用 self.color_func
  18. regexp : string or None (optional) //使用正则表达式分隔输入的文本
  19. collocations : bool, default=True //是否包括两个词的搭配
  20. colormap : string or matplotlib colormap, default=”viridis” //给每个单词随机分配颜色,若指定color_func,则忽略该方法。
  21. fit_words(frequencies) //根据词频生成词云【frequencies,为字典类型】
  22. generate(text) //根据文本生成词云
  23. generate_from_frequencies(frequencies[, ...]) //根据词频生成词云
  24. generate_from_text(text) //根据文本生成词云
  25. process_text(text) //将长文本分词并去除屏蔽词(此处指英语,中文分词还是需要自己用别的库先行实现,使用上面的 fit_words(frequencies) )
  26. recolor([random_state, color_func, colormap]) //对现有输出重新着色。重新上色会比重新生成整个词云快很多。
  27. to_array() //转化为 numpy array
  28. to_file(filename) //输出到文件

Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云的更多相关文章

  1. Python爬取b站任意up主所有视频弹幕

    爬取b站弹幕并不困难.要得到up主所有视频弹幕,我们首先进入up主视频页面,即https://space.bilibili.com/id号/video这个页面.按F12打开开发者菜单,刷新一下,在ne ...

  2. python爬取B站视频弹幕分析并制作词云

    1.分析网页 视频地址: www.bilibili.com/video/BV19E… 本身博主同时也是一名up主,虽然已经断更好久了,但是不妨碍我爬取弹幕信息来分析呀. 这次我选取的是自己 唯一的爆款 ...

  3. 用Python爬取B站、腾讯视频、爱奇艺和芒果TV视频弹幕!

    众所周知,弹幕,即在网络上观看视频时弹出的评论性字幕.不知道大家看视频的时候会不会点开弹幕,于我而言,弹幕是视频内容的良好补充,是一个组织良好的评论序列.通过分析弹幕,我们可以快速洞察广大观众对于视频 ...

  4. 萌新学习Python爬取B站弹幕+R语言分词demo说明

    代码地址如下:http://www.demodashi.com/demo/11578.html 一.写在前面 之前在简书首页看到了Python爬虫的介绍,于是就想着爬取B站弹幕并绘制词云,因此有了这样 ...

  5. Python爬取B站耗子尾汁、不讲武德出处的视频弹幕

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 前言 耗子喂汁是什么意思什么梗呢?可能很多人不知道,这个梗是出自马保国,经常上网的人可能听说过这个 ...

  6. Python爬取B站视频信息

    该文内容已失效,现已实现scrapy+scrapy-splash来爬取该网站视频及用户信息,由于B站的反爬封IP,以及网上的免费代理IP绝大部分失效,无法实现一个可靠的IP代理池,免费代理网站又是各种 ...

  7. Java + golang 爬取B站up主粉丝数

    自从学习了爬虫,就想在B站爬取点什么数据,最近看到一些个up主涨粉很快,于是对up主的粉丝数量产生了好奇,所以就有了标题~ 首先,我天真的以为通过up主个人空间的地址就能爬到 https://spac ...

  8. python爬取某站新闻,并分析最近新闻关键词

    在爬取某站时并做简单分析时,遇到如下问题和大家分享,避免犯错: 一丶网站的path为 /info/1013/13930.htm ,其中13930为不同新闻的 ID 值,但是这个数虽然为升序,但是没有任 ...

  9. Python 网络爬虫实战:爬取 B站《全职高手》20万条评论数据

    本周我们的目标是:B站(哔哩哔哩弹幕网 https://www.bilibili.com )视频评论数据. 我们都知道,B站有很多号称“镇站之宝”的视频,拥有着数量极其恐怖的评论和弹幕.所以这次我们的 ...

随机推荐

  1. PXC 57 二进制安装

    1.准备阶段 1.1 在三个节点上分别创建:用户组 用户组 目录 --用户组 用户组 #/usr/sbin/groupadd mysql #/usr/sbin/useradd -g mysql mys ...

  2. [原]Django-issue(1)---postgresql数据库连接密码错误

    环境: Django==1.9.13 psycopg2==2.7.5 Python 3.6.5 postgresql 1.18.1 配置django的时候出现问题 检查setting,问题点:由于安装 ...

  3. oracle客户端instantclient如何配置

    下载下来的instantclient-basic-nt-11.2.0.4.0.zip文件解压缩D:\Program Files\instantclient_11_2(可以选择自己的目录) (1) 增加 ...

  4. 关于Intel漏洞的学习

    这几天报道了Intel的漏洞,这里学习一下并做个记录. 报告:https://spectreattack.com/spectre.pdf #include <stdio.h> #inclu ...

  5. openshift 配置 bitbucket 的webhook

    参考 https://docs.openshift.org/latest/dev_guide/builds/triggering_builds.html oc set triggers bc < ...

  6. 10、DOM(文档对象模型)

    1.认识DOM html    骨架 css     装修 javascript 物业 ==DOM 打破上述三者的通道.== [注]script标签一般情况下要写在head标签. <div id ...

  7. STL之pair对组

    #include<iostream> #include<algorithm> #include<cstring> #include<cstdlib> u ...

  8. vue利用vue ui命令创建项目

    上次用git bash,用create 命令创建vue项目,这是玩个炫酷的------vue ui (前提是有安装node.js). 在目标文件  vue ui 可以看到他在8000端口出现了一个gu ...

  9. python 中字符串的格式化

    # 字符串格式化name = input("name:")age = int(input("age:"))job = input("job:" ...

  10. 做一个vue的todolist列表

    <template> <div id="app"> <input type="text" v-model="todo&q ...