yma16-logo

⭐前言

大家好,我是yma16,本文分享python的requests获取哔哩哔哩锻刀村的字幕并用分词划分可视化词云图展示。
该系列文章:
python爬虫_基本数据类型
python爬虫_函数的使用
python爬虫_requests的使用
python爬虫_selenuim可视化质量分
python爬虫_django+vue3可视化csdn用户质量分
python爬虫_正则表达式获取天气预报并用echarts折线图显示

requests简介

正则表达式(Regular expressions,也叫 REs、 regexs 或 regex patterns),是一个特殊的字符序列。
Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。
re 模块使 Python 语言拥有全部的正则表达式功能。
compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。
re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。

⭐获取字幕步骤

  1. 查找视频的cid参数
  2. 拼接字幕url
  3. requests去访问字幕url获取内容

💖 查找heartbeat接口

查找heartbeat接口中的cid参数,cid=1154635809
查找过程如下图:
cid-heartbeat

💖 字幕api接口

字幕接口
https://comment.bilibili.com/1154635809.xml
get访问即可拿到字幕
xml字幕内容如下
在这里插入图片描述

💖 正则提取p标签的内容

python抓取内容后,用re.complie提取字幕
代码如下:

import requests,re

def compile_font(text):
    c=re.compile(r'p="(.*?)">(.*?)<',re.S)
    result=re.findall(c,text)
    for i in result:
        value=i[1]
        with open('鬼灭之刃.txt','a+',encoding='utf-8') as f:
            f.write(value)

def request_post(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36",
        "origin": "https: // www.bilibili.com",
        "referer": "https://www.bilibili.com/bangumi/play/ss22088/?from=search&seid=17394404948182677638"
    }
    
    resp=requests.get(url,headers=headers)
    print(resp)
    text=resp.content.decode('utf-8')
    print('text',text)
    compile_font(text)


if __name__=='__main__':
    url="https://api.bilibili.com/x/v1/dm/list.so?oid=1154635809"
    request_post(url)

运行得到字幕的txt文件comment-font
inscode代码:

⭐分词

使用python的jiebaf分词
代码如下

import jieba
from wordcloud import WordCloud, ImageColorGenerator
from matplotlib import pyplot as plt
import numpy as np

with open('鬼灭之刃.txt', 'r', encoding="UTF-8") as file1:
    content = "".join(file1.readlines())
content_after = "\n".join(jieba.cut(content, cut_all=True))
print('content_after',content_after)
##添加的代码,把刚刚你保存好的图片用Image方法打开,
##然后用numpy转换了一下

wc = WordCloud(font_path="C:\Windows\Fonts\simsun.ttc",#字体路径
               background_color="white",#一下是图片背景颜色字体大小及尺寸大小
               max_words=5000,
               max_font_size=50,
               width=600,
               height=600,
              ).generate(content)
plt.imshow(wc)
wc.to_file('鬼灭之刃.png')


with open('鬼灭之刃分词.txt', 'a+', encoding='utf-8') as f:
    f.write(content_after)

分词效果
jieba-python

生成的词云图:
word-split-cloud

⭐结束

本文分享到这结束,如有错误或者不足之处欢迎指出!
scene

👍 点赞,是我创作的动力!
⭐️ 收藏,是我努力的方向!
✏️ 评论,是我进步的财富!
💖 感谢你的阅读!

Logo

前往低代码交流专区

更多推荐