爬取 48048 條評論,解讀 9.3 分的「毒液」是否值得一看?
11月,由湯姆•哈迪主演的“毒液:致命守護者”在國內上映,依託漫威的光環以及演員們精湛的演技,這部動作科幻片在貓眼評分得到豆瓣7.4的評分,口碑和票房都高於大多數同期上映的其他影片。
所以週日的時候跟基友去電影院去看了這場正邪共生的電影,100多人的影院座無虛席,不過看完之後對比其他漫威作品,我倒也沒覺得有多大的驚喜,覺得貓眼上的9.3評分的感受不符。
頭部的幾條評論顯然有些誇大,那大眾對“毒液”感受是怎麼呢?於是筆者動手開始分析起來。
獲取資料
首先要獲取資料,準備爬取貓眼上的電影評論作為本次分析樣本,PC官網上只顯示了電影的10條熱門短評,顯然不夠,於是準備從M端抓包找到評論介面。
介面連結:
介面中對我們本次抓取主要有用的引數是offset偏移量以及日期,這兩個條件限制了抓取的條數。分析介面結果:
這裡有使用者評論的相關資料,我們選取了地理位置(使用者為授權無法獲取)、評論內容、使用者名稱、評分以及評論時間的資料,通過python的requests模組開始爬取。匯入本次爬取需要的包,開始抓取資料。
def get_data(url):
headers = {
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1' }
html = requests.get(url, headers=headers)
if html.status_code ==200:
return html.content
else:
return none
其次是解析Json資料,每個介面有15條評論資料,10條熱門評論資料,我們將評論資料中使用者名稱、城市名、評論內容、評分、評論時間依次解析出來,並返回。
def parse_data(html):
json_data = json.loads(html)['cmts']
comments = []
try:
for item in json_data:
comment = {
'nickName': item['nickName'],
'cityName': item['cityName'] if 'cityName' in item else '',
'content': item['content'].strip().replace('\n', ''),
'score': item['score'],
'startTime': item['startTime']
}
comments.append(comment)
return comments
except Exception as e:
print(e)
接著我們將獲取到的資料儲存到本地。此過程中,對介面url中時間的處理借鑑了其他博主的爬蟲思路,將每次爬取的15條資料取最後一條的評論時間,減去一秒(防止重複),從該時間向前獲取直到影片上映時間,獲取所有資料。
def save():
start_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
end_time = '2018-11-09 00:00:00'
while start_time > end_time:
url = 'http://m.maoyan.com/mmdb/comments/movie/42964.json?_v_=yes&offset=15&startTime=' + start_time.replace(
' ', '%20')
html = None
try:
html = get_data(url)
except Exception as e:
time.sleep(0.5)
html = get_data(url)
else:
time.sleep(0.1)
comments =parse_data(html)
start_time = comments[14]['startTime']
print(start_time)
start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') + timedelta(seconds=-1)
start_time = datetime.strftime(start_time, '%Y-%m-%d %H:%M:%S')
for item in comments:
print(item)
with open('files/comments.txt', 'a', encoding='utf-8')as f:
f.write(item['nickName']+','+item['cityName'] +','+item['content']+','+str(item['score'])+ item['startTime'] + '\n')
if __name__ == '__main__':
url = 'http://m.maoyan.com/mmdb/comments/movie/42964.json?_v_=yes&offset=15&startTime=2018-11-19%2019%3A36%3A43'
html = get_data(url)
reusults = parse_data(html)
save()
最終抓取了48048條評論相關資料作為此次分析樣本。
資料視覺化
資料視覺化採用了pyecharts,按照地理位置製作了毒液觀眾群的分佈圖。部分程式碼如下:
geo = Geo('《毒液》觀眾位置分佈', '資料來源:貓眼-Ryan採集', **style.init_style)
attr, value = geo.cast(data)
geo.add('', attr, value, visual_range=[0, 1000],
visual_text_color='#fff', symbol_size=15,
is_visualmap=True, is_piecewise=False, visual_split_number=10)
geo.render('觀眾位置分佈-地理座標圖.html')
data_top20 = Counter(cities).most_common(20)
bar = Bar('《毒液》觀眾來源排行TOP20', '資料來源:貓眼-Ryan採集', title_pos='center', width=1200, height=600)
attr, value = bar.cast(data_top20)
bar.add('', attr, value, is_visualmap=True, visual_range=[0, 3500], visual_text_color='#fff', is_more_utils=True,
is_label_show=True)
bar.render('觀眾來源排行-柱狀圖.html')
從視覺化結果來看,“毒液”觀影人群以東部城市為主,觀影的top5城市為深圳、北京、上海、廣州、成都。
使用者評論,詞雲圖
只看觀眾分佈無法判斷大家對電影的喜好,所以我把通過jieba把評論分詞,最後通過wordcloud製作詞雲,作為大眾對該電影的綜合評價。
comments = []
with open('files/comments.txt', 'r', encoding='utf-8')as f:
rows = f.readlines()
try:
for row in rows:
comment = row.split(',')[2]
if comment != '':
comments.append(comment)
# print(city)
except Exception as e:
print(e)
comment_after_split = jieba.cut(str(comments), cut_all=False)
words = ' '.join(comment_after_split)
#多慮沒用的停止詞
stopwords = STOPWORDS.copy()
stopwords.add('電影')
stopwords.add('一部')
stopwords.add('一個')
stopwords.add('沒有')
stopwords.add('什麼')
stopwords.add('有點')
stopwords.add('感覺')
stopwords.add('毒液')
stopwords.add('就是')
stopwords.add('覺得')
bg_image = plt.imread('venmo1.jpg')
wc = WordCloud(width=1024, height=768, background_color='white', mask=bg_image, font_path='STKAITI.TTF',
stopwords=stopwords, max_font_size=400, random_state=50)
wc.generate_from_text(words)
plt.imshow(wc)
plt.axis('off')
plt.show()
從最終的詞雲結果上來看,大多數觀眾還是對“毒液”很滿意的。
更多案例請關注“思享會Club”公眾號或者關注思享會部落格:http://gkhelp.cn/