Python爬蟲豆瓣影評

         Python爬取豆瓣影評並生成詞雲,網上很多案例,我參考的這一篇 Python爬蟲實戰,具體步驟這篇文章講解的很詳細了,不過我在復現的過程中也遇到了很多問題,所以記錄一下。

#coding:utf-8

import warnings
warnings.filterwarnings("ignore")
import jieba    #分詞包
import numpy    #numpy計算包
import codecs   #codecs提供的open方法來指定打開的文件的語言編碼,它會在讀取的時候自動轉換爲內部unicode
import re
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from urllib import request
from bs4 import BeautifulSoup as bs
# %matplotlib inline

matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)
from wordcloud import WordCloud#詞雲包

#分析網頁函數
def getNowPlayingMovie_list():
    resp = request.urlopen('https://movie.douban.com/nowplaying/hangzhou/')
    html_data = resp.read().decode('utf-8')
    soup = bs(html_data, 'html.parser')
    nowplaying_movie = soup.find_all('div', id='nowplaying')
    nowplaying_movie_list = nowplaying_movie[0].find_all('li', class_='list-item')
    nowplaying_list = []
    for item in nowplaying_movie_list:
        nowplaying_dict = {}
        nowplaying_dict['id'] = item['data-subject']
        for tag_img_item in item.find_all('img'):
            nowplaying_dict['name'] = tag_img_item['alt']
            nowplaying_list.append(nowplaying_dict)
    return nowplaying_list

#爬取評論函數
def getCommentsById(movieId, pageNum):
    eachCommentList = [];
    if pageNum>0:
         start = (pageNum-1) * 20
    else:
        return False
    requrl = 'https://movie.douban.com/subject/' + movieId + '/comments' +'?' +'start=' + str(start) + '&limit=20'
    print(requrl)
    resp = request.urlopen(requrl)
    html_data = resp.read().decode('utf-8')
    soup = bs(html_data, 'html.parser')
    comment_div_lits = soup.find_all('div', class_='comment')
    for item in comment_div_lits:
        if item.find_all('p')[0].span.string is not None:
            eachCommentList.append(item.find_all('p')[0].span.string)
    return eachCommentList

def main():
    #循環獲取第一個電影的前10頁評論
    commentList = []
    NowPlayingMovie_list = getNowPlayingMovie_list()
    for i in range(10):
        num = i + 1
        commentList_temp = getCommentsById(NowPlayingMovie_list[0]['id'], num)
        commentList.append(commentList_temp)

    #將列表中的數據轉換爲字符串
    comments = ''
    for k in range(len(commentList)):
        comments = comments + (str(commentList[k])).strip()

    #使用正則表達式去除標點符號
    pattern = re.compile(r'[\u4e00-\u9fa5]+')
    filterdata = re.findall(pattern, comments)
    cleaned_comments = ''.join(filterdata)

    #使用結巴分詞進行中文分詞
    segment = jieba.lcut(cleaned_comments)
    words_df=pd.DataFrame({'segment':segment})

    #去掉停用詞
    stopwords=pd.read_csv("stopwords.txt",index_col=False,quoting=3,sep="\t",names=['stopword'], encoding='gbk')#quoting=3全不引用
    words_df=words_df[~words_df.segment.isin(stopwords.stopword)]

    #統計詞頻
    words_stat=words_df.groupby(by=['segment'])['segment'].agg({"計數":numpy.size})
    words_stat=words_stat.reset_index().sort_values(by=["計數"],ascending=False)

    #用詞雲進行顯示
    # wordcloud=WordCloud(font_path="simhei.ttf",background_color="white",max_font_size=80)
    word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values}

    word_frequence_list = []
    for key in word_frequence:
        temp = (key,word_frequence[key])
        word_frequence_list.append(temp)
    wfl = dict(word_frequence_list)

    wordcloud = WordCloud(scale=5,font_path='./fonts/simhei.ttf',max_font_size=40, relative_scaling=.5).fit_words(wfl)
    plt.figure()
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()

#主函數
main()

不過在搬運的過程中也出現一些小bug以及小tips,記錄下來。
(1) %matplotlib inline這一個語句是jupyter中的,在pycharm中會顯示invalid syntax(無效語法),所以註釋掉就OK,在jupyter中這一句的意思。當你調用matplotlib.pyplot的繪圖函數plot()進行繪圖的時候,或者生成一個figure畫布的時候,可以直接在你的python console裏面生成圖像。
(2)stopwords.txt可以直接百度搜索下載,否則會提示找不着文件。
(3)最後結果只顯示框框沒有文字(如下圖)
在這裏插入圖片描述
這是因爲中文不識別,所以在在Wordcloud中加入 font_path=’./fonts/simhei.ttf’ 即可
在這裏插入圖片描述
(4)報錯:‘list’ object has no attribute ‘items’’,這是由於fit_words需要傳入字典格式,而傳入列表會報錯。所以要轉換格式(wfl = dict(word_frequence_list))。
(5)提取評論結果爲空,有兩種方法可以解決:
        a.把第二個遍歷裏的item.string 改成 item.span.string;
        b.直接在find_all的語句改成 find_all(‘span’, ‘short’)。
        說明一下, 首先p元素裏面還有一個span元素, 如果你直接.string的話正常應該是****這樣的形式。但爲什麼你的代碼裏卻什麼都沒有呢, 因爲requests的響應內容裏面,會有\n這個換行符。 也就是說你的p元素裏面不止有一個span元素,還有2個\n分別在span的兩邊,這個換行符對於bs4來說也是一個元素,而string只能用於裏面只有一個元素的情況。所以你的string方法什麼都沒有。
(6)stopwords可能會報解碼錯誤,這取決於你下載的stopwords.txt的編碼方式,通常就是gbk或utf-8這兩種,改一下就好。

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