Python3爬取B站视频弹幕

开发 后端
本文通过8个步骤教你如何使用Python3爬取B站的视频弹幕,快往下看看吧。

 [[215973]]

需要准备的环境:

  1. 一个B站账号,需要先登录,否则不能查看历史弹幕记录
  2. 联网的电脑和顺手的浏览器,我用的Chrome
  3. Python3环境以及request模块,安装使用命令,换源比较快:
  1. pip3 install  request -i http://pypi.douban.com/simple  

爬取步骤:

1.登录后打开需要爬取的视频页面,打开开发者工具台,Chrome可以使用F12快捷键,选择network监听请求  

 

2.点击查看历史弹幕,获取请求  

 

  

其中rolldate后面的数字表示该视频对应的弹幕号,返回的数据中timestamp表示弹幕日期,new表示数目 

 

4.在查看历史弹幕中任选一天,查看,会发出新的请求

dmroll ,时间戳,弹幕号,表示获取该日期的弹幕,1507564800 表示2017/10/10 0:0:0 

 

 

 

 

 

该请求返回xml数据 

 

5.使用正则表达式获取所有弹幕消息,匹配模式

 

  1. '<d p=".*?">(.*?)</d>'  

6.拼接字符串,将所有弹幕保存到本地文件即可 

  1. with open('content.txt', mode='w+', encoding='utf8'as f:    f.write(content)  

7.参考代码如下,将弹幕按照日期保存为单个文件...因为太多了... 

 

  1. import requests 
  2.  
  3. import re 
  4.  
  5. import time  
  6.  
  7. """    爬取哔哩哔哩视频弹幕信息"""  
  8.  
  9. # 2043618 是视频的弹幕标号,这个地址会返回时间列表 
  10.  
  11. # https://www.bilibili.com/video/av1349282 
  12.  
  13. url = 'https://comment.bilibili.com/rolldate,2043618' 
  14.  
  15. # 获取弹幕的id 2043618 
  16.  
  17. video_id = url.split(',')[-1]print(video_id) 
  18.  
  19. # 获取json文件 
  20.  
  21. html = requests.get(url) 
  22.  
  23. # print(html.json()) 
  24.  
  25.   
  26.  
  27. # 生成时间戳列表 
  28.  
  29. time_list = [i['timestamp'for i in html.json()] 
  30.  
  31. # print(time_list) 
  32.  
  33.   
  34.  
  35. # 获取弹幕网址格式 'https://comment.bilibili.com/dmroll,时间戳,弹幕号' 
  36.  
  37.   
  38.  
  39. # 弹幕内容,由于总弹幕量太大,将每个弹幕文件分别保存 
  40.  
  41. for i in time_list:    content = ''    j = 'https://comment.bilibili.com/dmroll,{0},{1}'.format(i, video_id)    print(j)    text = requests.get(j).text 
  42.  
  43.     # 匹配弹幕内容    res = re.findall('<d p=".*?">(.*?)</d>', text)     
  44.  
  45.     # 将时间戳转化为日期形式,需要把字符串转为整数    timeArray = time.localtime(int(i))    date_time = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)    print(date_time)    content += date_time + ' 
  46.  
  47. '    for k in res:        content += k + ' 
  48.  
  49. '    content += ' 
  50.  
  51. '    file_path = 'txt/{}.txt'.format(time.strftime("%Y_%m_%d", timeArray))    print(file_path)     
  52.  
  53.     with open(file_path, mode='w+', encoding='utf8'as f:        f.write(content)  

8.最终效果 

 

 

责任编辑:庞桂玉 来源: 程序员共读
相关推荐

2017-11-17 19:56:46

爬虫视频信息数据库

2021-10-29 07:49:23

Python弹幕播放

2021-06-02 15:10:20

PythonScrapy视频

2020-12-02 09:42:42

PythonApp抖音视频

2022-12-26 00:00:05

Python爬虫B站弹幕

2021-09-09 06:18:04

交互功能弹幕

2020-10-20 14:12:54

B站开源弹幕

2016-12-07 11:18:58

Python爬虫网站

2017-05-24 15:07:19

Python爬虫爬取

2018-02-24 18:11:11

2020-10-12 08:19:43

Python爬虫网页数据

2020-11-03 14:10:45

Python爬取天气爬虫

2019-01-02 12:23:30

Python金融数据爬取

2019-01-11 10:22:31

Python数据爬取

2021-01-24 16:40:00

Python爬取网站编程语言

2019-04-24 09:48:54

2024-03-01 18:52:31

视频超分算法

2018-01-09 14:19:14

PythonAndroid爬虫

2015-05-07 09:32:55

APP开源
点赞
收藏

51CTO技术栈公众号