python爬蟲(BeautifulSoup)爬取B站視頻字幕,簡單的數據處理(講字幕寫入到CSV文件中)

上文,我們爬取到B站視頻的字幕:https://www.cnblogs.com/becks/p/14540355.html

這篇,講講怎麼把爬到的字幕寫到CSV文件中,以便用於後面的分析

 

本文主要用到“pandas”這個庫對數據進行處理

import pandas as pd

首先需要對爬取到的內容進行數據提取

comments = [comment.text for comment in results]#從爬取的數據中取出彈幕數據,返回文本內容

執行後如下圖

 

然後生成字典

comments_dict = {'comments': comments}#創建字典,把字幕內容裝入字典

 

處理數據,使數據以表格形式展示

df = pd.DataFrame(comments_dict)#格式化字幕字典,將字幕內容已表格格式顯示

效果如下圖

 

 

把格式化後的數據,存到CSV文件中

df.to_csv('B站字母.csv', encoding='utf-8-sig')#格式化後的字幕內容寫入到CSV文件中

執行後,會在腳本同目錄下生成CSV文件,文件內容如下圖

 

 

 全部腳本

# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
import requests
import re
import pandas as pd

url = 'http://comment.bilibili.com/309778762.xml'
html = requests.get(url)
html.encoding='utf8'

soup = BeautifulSoup(html.text,'lxml')
results = soup.find_all('d')

comments = [comment.text for comment in results]#從爬取的數據中取出彈幕數據,返回文本內容
comments_dict = {'comments': comments}#創建字典,把字幕內容裝入字典
df = pd.DataFrame(comments_dict)#格式化字幕字典,將字幕內容已表格格式顯示
df.to_csv('B站字母.csv', encoding='utf-8-sig')#格式化後的字幕內容寫入到CSV文件中

 

格式化數據“pd.DataFrame”函數的用法可以參考,https://www.cnblogs.com/andrew-address/p/13040035.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章