Python爬取爬取騰訊影片彈幕影片講解
https://www.bilibili.com/video/BV1954y1r7pi/
前言
「《奔跑吧》第五季」已經播出兩期了,節目以“黃河生態經濟帶”沿線地區為依託,透過創新遊戲設定、直播帶貨扶貧等新形式,展現黃河流域的重要地位,描繪黃河生態經濟帶城市“文化之美”。
資料獲取騰訊影片評論要點選「檢視更多評論」才能載入更多資料,很明顯是一個動態網頁,評論內容使用了「Ajax動態載入技術」。因此,我們需要找到「真實URL」,然後再請求資料。透過真實URL獲取到cursor=?和_=?這兩個引數即可。核心程式碼如下:
def main(): #初始頁面的_=? page=1607948139253 #初始待重新整理頁面的cursor=? lastId="0" for i in range(1,1000): time.sleep(1) html = get_content(page,lastId) #獲取評論資料 commentlist=get_comment(html) print("------第"+str(i)+"輪頁面評論------") k = 0 for j in range(1,len(commentlist)): comment = commentlist[j] k += 1 print('第%s條評論:%s'%(k,comment)) #獲取下一輪重新整理頁ID lastId=get_lastId(html) page += 1if __name__ == '__main__': main()
資料處理匯入相關包
import jiebaimport reimport numpy as npimport pandas as pd import matplotlib.pyplot as plt from pyecharts.charts import *from pyecharts import options as opts from pyecharts.globals import ThemeType import stylecloudfrom IPython.display import Image
匯入評論資料分別爬取了兩期評論,因此需要分別讀取併合並所有資料。
df1 = pd.read_csv('/騰訊評論/paonan.csv',names=['評論內容'])df2 = pd.read_csv('/騰訊評論/paonan1.csv',names=['評論內容'])df = pd.concat([df1,df2])df.head(10)
資料預覽
df.info()df['評論內容'] = df['評論內容'].astype('str')
<class 'pandas.core.frame.DataFrame'>Int64Index:21307 entries, 0 to 11833Data columns (total 1 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 評論內容 21199 non-null objectdtypes: object(1)memory usage: 332.9+ KB
刪除重複評論
df = df.drop_duplicates()
刪除缺失資料df = df.dropna()
增加評論型別
人為劃分評論型別,20字以下為短評,20-50字為中評,50字以上為長評。
cut = lambda x : '短評'if len(x) <= 20else ('中評'if len(x) <=50else'長評')df['評論型別'] = df['評論內容'].map(cut)
提取演員關鍵詞
根據評論內容關鍵詞,提取出人物提及欄位。
tmp=[]for i in df["評論內容"]: if"黑牛"in i: tmp.append("李晨") elif"楊穎"in i: tmp.append("楊穎") elif"沙溢"in i: tmp.append("沙溢") elif"坤"in i: tmp.append("蔡徐坤") elif"毅"in i: tmp.append("成毅") elif"一桐"in i: tmp.append("李一桐") else: tmp.append("其他")df['人物提及'] = tmp
機械壓縮去重定義一個機械壓縮函式:
def yasuo(st): for i in range(1,int(len(st)/2)+1): for j in range(len(st)): if st[j:j+i] == st[j+i:j+2*i]: k = j + i while st[k:k+i] == st[k+i:k+2*i] and k<len(st): k = k + i st = st[:j] + st[k:] return styasuo(st="123")
呼叫函式,對評論內容進行機械壓縮去重:
df = df[df["評論內容"].apply(len)>=4]df = df.dropna()
資料視覺化整體評論情況
# 繪製詞雲圖text1 = get_cut_words(content_series=df['評論內容'])stylecloud.gen_stylecloud(text=' '.join(text1), max_words=1000, collocations=False, font_path='演示悠然小楷.ttf', icon_name='fas fa-video', size=653, #palette='matplotlib.Inferno_9', output_name='./評論.png')Image(filename='./評論.png')
透過對所有評論進行詞雲圖繪製,我們發現「成毅」提及最多,對於最新跑男的看法,大家表現出非一致的看法。有人說「好看、喜歡」,有人說「沒意思」。另外,評論中還多次提到往期節目中的嘉賓,如「陳赫、鄭凱、郭麒麟」等,沒有比較就沒有傷害,很多人還是更喜歡往期的跑男的。
評論型別分佈df2 = df.groupby('評論型別')['評論內容'].count()df2 = df2.sort_values(ascending=False) regions = df2.index.to_list()values = df2.to_list()c = ( Pie(init_opts=opts.InitOpts(theme=ThemeType.CHALK)) .add("", zip(regions,values),radius=["40%", "70%"]) .set_global_opts(title_opts=opts.TitleOpts(title="評論型別佔比",subtitle="資料來源:騰訊影片",pos_top="2%",pos_left = 'center')) .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{d}%",font_size=18)) )c.render_notebook()
演員角色提及df8 = df["人物提及"].value_counts(ascending=True)[:6]print(df8.index.to_list())print(df8.to_list())c = ( Bar(init_opts=opts.InitOpts(theme=ThemeType.CHALK)) .add_xaxis(df8.index.to_list()) .add_yaxis("",df8.to_list()).reversal_axis() .set_global_opts(title_opts=opts.TitleOpts(title="人物提及次數",subtitle="資料來源:騰訊影片 ",pos_left = 'top'), xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=13)), #更改橫座標字型大小 yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=13)), #更改縱座標字型大小 ) .set_series_opts(label_opts=opts.LabelOpts(font_size=16,position='right')) )c.render_notebook()
新成員「成毅」被觀眾提及次數最多,達到790次,其次是「蔡徐坤」,被提及452次。李晨被提及次數最少。
成毅評論詞雲cy = df[df["人物提及"]=="成毅"]text = get_cut_words(content_series=cy['評論內容'])stylecloud.gen_stylecloud(text=' '.join(text), max_words=500, collocations=False, font_path='演示悠然小楷.ttf', icon_name='fas fa-comments', #palette='matplotlib.Inferno_9', size=653, output_name='./dinghui.png')Image(filename='./dinghui.png')
成毅在新一季跑男的表現被網友廣泛議論,認可他的觀眾「喜歡、期待、可愛」他的表現。也有相當多的觀眾覺得他「智商」有問題,是個「遊戲黑洞」,而且很「搞笑」。
最新評論