[python爬蟲]豆瓣電影Top250簡單數據分析繪圖

一:簡介

通過抓取豆瓣電影Top250的數據,分別進行了三個數據統計,分別是:上榜的電影上映的年份,該年份總共上榜的電影數量,數量為0的就沒有統計了;各個國家地區出品的電影數量;250部電影的各個類型標簽的數量。

二:源代碼
#coding=utf-8
import requests
from bs4 import BeautifulSoup
import os, socket, re
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

class Spider:
    def __init__(self, url='https://movie.douban.com/top250'):
        self.url = url
        self.header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
        }

    def mkdir(self, path):
        path = path.strip()
        isExists = os.path.exists(os.path.join("D:\mdouban", path))
        if not isExists:
            os.makedirs(os.path.join("D:\mdouban", path))
            os.chdir(os.path.join("D:\mdouban", path))
        else:
            os.chdir(os.path.join("D:\mdouban", path))
        return os.path.abspath('.')

    #獲取BeautifulSoup
    def get_soup(self, link):
        html = requests.get(link, headers=self.header)
        html.encoding = html.apparent_encoding
        soup = BeautifulSoup(html.text, 'lxml')
        return soup


if __name__ == '__main__':
    socket.setdefaulttimeout(20)
    spider = Spider()
    path = spider.mkdir('top250')
    print('starting get data from douban...')

    def autolabel(rects, ax, xpos='center'): #設置顯示每一個條形圖的值
        """
        Attach a text label above each bar in *rects*, displaying its height.

        *xpos* indicates which side to place the text w.r.t. the center of
        the bar. It can be one of the following {'center', 'right', 'left'}.
        """

        xpos = xpos.lower()  # normalize the case of the parameter
        ha = {'center': 'center', 'right': 'left', 'left': 'right'}
        offset = {'center': 0.5, 'right': 0.57, 'left': 0.43}  # x_txt = x + w*off

        for rect in rects:
            height = rect.get_height()
            ax.text(rect.get_x() + rect.get_width() * offset[xpos], 1.01 * height,
                    '{}'.format(height), ha=ha[xpos], va='bottom', size=6.8)

    def drawYearPlot(num_list, name_list):      #繪制X軸為年份,Y軸為電影數量的柱狀圖
        ind = np.arange(len(name_list))
        fig, ax = plt.subplots()
        ax.set_xlabel('year')
        ax.set_ylabel('numbers')
        ax.set_title('Douban top 250 movie numbers by year')

        rext = ax.bar(ind, num_list, color='b', tick_label=name_list)
        autolabel(rext, ax)
        plt.xticks(np.arange(len(name_list)), rotation=-90, size=7.2)  # 設置X軸坐標的屬性

        fig = plt.gcf()
        fig.set_size_inches(15.5, 10.5)  # 設置圖片大小
        plt.savefig('D:/mdouban/douban_year.png', dpi=200)  # 保存統計圖到本地,必須在show()方法前調用,否則得到的是一張空白圖片,dpi是分辨率
        plt.show()
        plt.close()

    def drawCountryPlot(cry_list):      #繪制X軸為國家地區,Y軸為電影數量的柱狀圖
        sta = {}
        for i in cry_list:  #統計各個國家的電影數量
            if not sta.__contains__(i):
                sta[i] = 1
            else:
                sta[i] += 1
        num_l = []  #數量
        country_list = [] #國家地區
        for key, values in sta.items():
            country_list.append(key)
            num_l.append(values)

        ind = np.arange(len(country_list))
        fig, ax = plt.subplots()
        ax.set_xlabel('country')
        ax.set_ylabel('numbers')
        ax.set_title('Douban top 250 movie numbers by country')

        rext = ax.bar(ind, num_l, color='b', tick_label=country_list)
        autolabel(rext, ax)
        plt.xticks(np.arange(len(country_list)), size=7.2)  # 設置X軸坐標的屬性

        fig = plt.gcf()
        fig.set_size_inches(15.5, 10.5)  # 設置圖片大小
        plt.savefig('D:/mdouban/douban_country.png', dpi=200)  # 保存統計圖到本地,必須在show()方法前調用,否則得到的是一張空白圖片,dpi是分辨率
        plt.show()
        plt.close()

    def drawTypePlot(typ_list):     #繪制X軸為電影的標簽,Y軸為數量的柱狀圖
        sta = {}
        for i in typ_list:  #統計各個國家的電影數量
            if not sta.__contains__(i):
                sta[i] = 1
            else:
                sta[i] += 1
        num_l = []  #數量
        tp_list = [] #電影類型
        for key, values in sta.items():
            tp_list.append(key)
            num_l.append(values)

        ind = np.arange(len(tp_list))
        fig, ax = plt.subplots()
        ax.set_xlabel('type')
        ax.set_ylabel('numbers')
        ax.set_title('Douban top 250 movie number by type')

        rext = ax.bar(ind, num_l, color='b', tick_label=tp_list)
        autolabel(rext, ax)
        plt.xticks(np.arange(len(tp_list)), size=7.2)  # 設置X軸坐標的屬性

        fig = plt.gcf()
        fig.set_size_inches(15.5, 10.5)  # 設置圖片大小
        plt.savefig('D:/mdouban/douban_type.png', dpi=200)  # 保存統計圖到本地,必須在show()方法前調用,否則得到的是一張空白圖片,dpi是分辨率
        plt.show()
        plt.close()

    #top250共十頁
    ys = []     #存儲年份
    cs = []     #存儲國家地區
    ts = []     #存儲電影類別
    #解決matplotlib顯示中文亂碼問題
    mpl.rcParams['font.sans-serif'] = ['SimHei']  # 指定默認字體 SimHei為黑體
    mpl.rcParams['axes.unicode_minus'] = False  # 用來正常顯示負號
    x = 1
    for i in range(1, 11):
        if i == 1:
            url = spider.url
        else:
            url = spider.url + '?start=' + str(25*(i-1)) + '&filter='   #后面9頁的鏈接需要拼接
        main_soup = spider.get_soup(url)
        ol_grid = main_soup.find('ol', class_='grid_view')
        li = ol_grid.find_all('li')

        for l in li:
            em_rank = l.find('em').get_text()

            div_hd = l.find('div', class_='hd')
            a = div_hd.find('a')
            title = a.find('span', class_='title').get_text()

            p_info = l.find('p', class_='').get_text()
            s_c = p_info.split('/')[-2].strip()
            country = s_c.split()[0]        #獲取國家地區字段,取第一個
            cs.append(country)

            l_typ = p_info.split('/')[-1].strip().split()   #獲取電影類型的數組
            for typ in l_typ:
                ts.append(typ)

            s1 = ''.join(p_info.split()) #去掉字符串中的\xa0
            l_s = s1.split('/')
            if x == 80:
                year = '1961'         #第80的大鬧天宮上映了多次,特殊處理
            else:
                year = l_s[-3][-4:]     #電影的上映年份
            x += 1
            ys.append(year)

            div_star = l.find('div', class_='star')
            rating_num = div_star.find('span', class_='rating_num').get_text()
            review = div_star.find_all('span')[3].get_text()

            div_bd = l.find('div', class_='bd')
            q = div_bd.find('span', class_='inq')
            if q != None:   #部分電影是沒有短評的,所以需要判斷
                quote = q.get_text()
            else:
                quote = '無'
    name_list = []
    sta = {}
    for i in range(1931, 2018):     #柱狀圖的X軸坐標
        name_list.append(i)
        sta[str(i)] = 0

    for x in ys:        #統計從1931到2017每年在榜單中的電影數量
        sta[x] += 1
    num_list = []
    name_list1 = []
    for key, value in sta.items():
        if value > 0:       #只顯示電影數量大于0的
            name_list1.append(str(key))
            num_list.append(value)
    drawYearPlot(num_list, name_list1)
    drawCountryPlot(cs)
    drawTypePlot(ts)

    print('over!')
三:生成的柱狀圖
douban_country.png
douban_type.png
douban_year.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容