1. 程式人生 > 實用技巧 >爬蟲:python採集豆瓣影評資訊並進行資料分析

爬蟲:python採集豆瓣影評資訊並進行資料分析

前言:最近比較有時間,替一個同學完成了一個簡單的爬蟲和資料分析任務,具體的要求是爬取復仇者聯盟4 的豆瓣影評資訊並進行簡單的資料分析,這裡的資料分析指的是提取關鍵詞並進行詞雲分析以及按照時間進行熱度分析,分析比較簡單,後續可以繼續完善。

首先,獻上資料採集和分析的結果。

短評資料

按照該同學的要求,只採集了1000條資料,有需要更多資料的同學可自行修改採集的限制即可

下面,我們就來詳細描述下如何完成資料採集和資料分析的工作的

首先,爬蟲的第一步,分析頁面元素,開啟網頁,按下F12,檢視資料請求

從上往下,依次尋找,我們可以發現數據就存在於第一個請求中

我們可以分析下這個請求,點選翻頁,多請求幾個頁面

我們可以知道他的翻頁規律是由start和limit這兩個引數來控制的,start表示第幾頁,limit表示每頁多少條

知道他的分頁規律後,我們需要定位我們需要採集的元素,我們這裡需要採集短評內容、釋出人資訊、評價指數、評價時間,贊同數等

這裡我們選擇的是etree+xpath解析資料,這裡我給大家演示下如何定位短評內容,我們採用瀏覽器上的選中元素的功能,選中元素後,檢視元素的位置

分析對應的html元素,首先找到改元素最可靠的頂級元素,這裡我們可以很容易的發現這個元素是位於id="comments"這個div元素下面,一般而言,以id為準的元素不會發生太大的變化,接著,我們繼續往下找,找到對應元素的上級中比較可靠的元素,比如class,這裡有個小技巧,我們可以利用瀏覽器的$x方法驗證我們的xpath是否正確,像下面這樣

這樣我們就可以很容易的採集到短評資料了,程式碼如下

def start_spider(self):
        result_list = []
        for i in range(0,50):
            start = i
            reponse = requests.get(self.target_url.format(start),headers=self.headers)
            # print(reponse.text)
            html = etree.HTML(str(reponse.content,'utf-8'))
            # 短評列表
            short_list = html.xpath('//div[@id="comments"]/div[@class="comment-item"]//span[@class="short"]/text()')
            print(short_list)

            times = html.xpath('//div[@class="comment-item"]//span[@class="comment-info"]/span[2]/@class')

            complte_times = html.xpath('//div[@class="comment-item"]//span[@class="comment-info"]/span[3]/@title')

            votes = html.xpath('//div[@class="comment-item"]//div[@class="comment"]/h3/span[@class="comment-vote"]/span[@class="votes"]/text()') # 贊同量

採集了短評資料,我們還需要採集釋出人的一些其他資訊,比如註冊時間,常駐城市等等

因此我們需要根據這個連結去使用者的主頁完成資訊採集

採集的原理也是一樣,利用xpath解析網頁資料,不過這個連結需要注意的是,需要登入後才能請求,我這個爬蟲裡面的解決辦法是利用cookie,

當我們用賬戶登入後,隨便檢視一個請求,都能發現我們的cookie資訊

直接複製這段請求到請求的header裡就行

程式碼如下

headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
        'Cookie': 'll="118281"; bid=1E8tHh1UO7k; __utma=30149280.787827060.1593838175.1593838175.1593838175.1; __utmc=30149280; __utmz=30149280.1593838175.1.1.utmcsr=so.com|utmccn=(referral)|utmcmd=referral|utmcct=/link; ap_v=0,6.0; _vwo_uuid_v2=DFE5584FB8092E19E1C48ACB6A8C99E62|d5d4f0c4ca4c47a6ddcacacff97040ad; __gads=ID=5490f395fcb95985:T=1593838190:S=ALNI_Mbd_y4lD5XgT1pqnwj9gyQQasX2Nw; dbcl2="218965771:ytN/j1jGo58"; ck=7U_Q; __guid=236236167.3893834060458141000.1593840219409.0322; _pk_ref.100001.8cb4=%5B%22%22%2C%22%22%2C1593840220%2C%22https%3A%2F%2Faccounts.douban.com%2Faccounts%2Fpassport%2Fregister%22%5D; _pk_ses.100001.8cb4=*; push_noty_num=0; push_doumail_num=0; __utmt=1; __utmv=30149280.21896; __yadk_uid=5q5tgoXkHZk2p7qqUcXhzcqZF8yK4kpa; monitor_count=4; _pk_id.100001.8cb4=a34ccb6950d8365b.1593840220.1.1593840306.1593840220.; __utmb=30149280.9.10.1593838175'
    }

            # 使用者連結列表
            user_list = html.xpath('//div[@id="comments"]/div[@class="comment-item"]//span[@class="comment-info"]/a/@href')
            for i in range(len(user_list)):
                url = user_list[i]
                item = {'short':self.clear_character_chinese(str(short_list[i]))}
                reponse = requests.get(url,headers=self.headers)
                html = etree.HTML(reponse.text)
                city = html.xpath('//div[@class="user-info"]/a/text()')
                join_date = html.xpath('//div[@class="user-info"]/div[@class="pl"]/text()')
                if(city != None):
                    if(len(city) > 0):
                        item['city'] = self.clear_character_chinese(city[0])
                    else:
                        continue
                if(join_date != None):
                    if(len(join_date)>1):
                        item['join_date'] = self.clear_character_chinese(join_date[1]).replace("加入","")
                    elif(len(join_date)>0):
                        item['join_date'] = self.clear_character_chinese(join_date[0]).replace("加入","")
                    else:
                        continue
                user_name = html.xpath('//div[@class="info"]/h1/text()')

爬蟲的程式碼基本就這些,我們這裡是儲存為excel檔案,程式碼如下

    # # 儲存資料到excel檔案
    def saveToCsv(self,data):
        print(data)
        wb = Workbook()
        ws = wb.active
        ws.append(['短評內容','評分','贊同量','評價日期','評價時間', '使用者名稱', '常住地址','註冊時間'])
        for item in data:
            line = [item['short'], item['time'],item['vote'],item['complete_time'],item['detail_time'], item['userName'],item['city'],item['join_date']]
            ws.append(line)
            wb.save('douban.xlsx')

儲存的資料如開篇所示

獲得了資料之後,我們利用wordcloud進行詞雲分析,分別分析出全部、好評、中評、差評等資料的詞雲,程式碼如下

    # 讀取短評內容
    def read_short_data(self,word_type):
        data = []
        workbook1=load_workbook('douban.xlsx')
        sheet=workbook1.get_sheet_by_name("Sheet")
        count = 0
        for row in sheet.iter_rows():
            if(count == 0):
                count = 1
                continue
            print(row[0].value)
            short = row[0].value
            short_type = row[1].value
            if (word_type == 1):
                if (int(short_type)<40):
                    continue
            elif(word_type == 2):
                if (int(short_type)>=40 or int(short_type)<=20):
                    continue
            elif(word_type == 3):
                if (int(short_type)>20):
                        continue
            short = self.clean_stopwords(short)
            data.append(short)
        return ";".join(data)

    def generWord(self,word_type):
        # 查詢資料
        content = self.read_short_data(word_type)
        msg = "全部"
        if(word_type == 1):
            msg = "好評"
        elif(word_type == 2):
            msg = "中評"
        elif(word_type == 3):
            msg = "差評"
        self.get_image(content,"douban_{}.png".format(msg))

    # 生成詞雲
    def get_image(self,data,savePath):
        text  = self.trans_CN(data)
        wordcloud = WordCloud(
            background_color="white",
            font_path = "C:\\Windows\\Fonts\\msyh.ttc"
        ).generate(text)
        # image_produce = wordcloud.to_image()
        # image_produce.show()
        wordcloud.to_file(savePath)

詞雲出來的結果如下所示

好評中評差評全部

分析了詞雲,我們接著完成時間分析,因為採集的資料太少,分析結果不是很好,程式碼如下

   # 時間分析
    def group_by(self,column):
        workbook1=load_workbook('douban.xlsx')
        sheet=workbook1.get_sheet_by_name("Sheet")
        count = 0
        item={}
        for row in sheet.iter_rows():
            if(count == 0):
                count = 1
                continue
            print(row[0].value)
            join_time = row[column].value
            if (column == 4):
                join_time_str = join_time.split(':')[0]
                join_time = int(join_time_str)
            if(join_time in item):
                item[join_time] = item[join_time]+1
            else:
                item[join_time] = 1
        x = []
        y = []
        for i in sorted (item) : 
            if(column == 4):
                join_time = str(int(i))+'點至'+str(int(i)+1)+'點'
                x.append(join_time)
            else:
                x.append(i)
            y.append(item[i])
        if(column == 4):
            plt.xlabel('日期')
        else:
            plt.xlabel('時刻')
        plt.ylabel('短評數量')
        print(y)
        plt.plot(x, y)
        plt.xticks(x, x, rotation=30)
        if(column == 4):
            plt.title('短評數量隨著時刻的變化關係')
        else:
            plt.title('短評數量隨著日期的變化關係')
        plt.rcParams['font.sans-serif'] = 'SimHei'
        plt.rcParams['axes.unicode_minus'] = False
        if(column == 4):
            plt.savefig('group_bytime.png')
        else:
            plt.savefig('group_bydate.png')

這裡只分析了短評數量的變化,實際上資料中還有很多可以分析的內容,分析結果如下

通過這兩個分析結果,我們可以大致看出,復仇者聯盟這部電影關心的人數隨著時間的推進,下降很多,這說明大家都是奔著第一天的熱度去的,畢竟被劇透了就沒啥好看的了,分析這個時刻的變化,發現人們都喜歡在深夜2、3點的時候進行評價,可能夜貓子比較多,由於這只是一個學生的簡單作業,就沒有做太多的分析工作。

以上就是本文的全部內容,如果需要完整原始碼的可聯絡站長或者訪問右側的爬蟲開源專案,上面有該專案的完整程式碼及分析結果,如果對你有幫助,不妨star一下

本文首發於

爬蟲:python採集豆瓣影評資訊並進行資料分析