爬取中国票房网数据并进行可视化

image.png

    这里主要是对年度票房信息进行操作,url构造、数据解析方面都是比较简单的了,这里就只是简单说一下

爬虫

1. 请求网站

request请求网站,返回源码信息

def get_Html(url):
    r = requests.get(url, headers=headers)
    r.encoding = r.apparent_encoding
    return r.text

2. 获取电影数据保存至字典

    因为数据不多,我们就对页面可视的所有数据进行抓取,这里用到了lxml里面的etree解析网页,用xpath获取对应的数据项然后保存,代码比较简单,过程数据项英文翻译过来就懂了,就不做太多注释了

def get_Info(text):
    info = {}
    info['movie_name'] = []
    info['movie_type'] = []
    info['movie_type'] = []
    info['total'] = []
    info['price_average'] = []
    info['session_average'] = []
    info['origin'] = []
    info['time'] = []
    tree = etree.HTML(text)
    movies = tree.xpath('//table[@id="tbContent"]//tr')[1:]
    for movie in movies:
        movie_name = movie.xpath('./td[1]/a/p/text()')[0]
        if movie.xpath('./td[2]/text()'):
            movie_type = movie.xpath('./td[2]/text()')[0]
        total = movie.xpath('./td[3]/text()')[0]
        price_average = movie.xpath('./td[4]/text()')[0]
        session_average = movie.xpath('./td[5]/text()')[0]
        if movie.xpath('./td[6]/text()'):
            origin = movie.xpath('./td[6]/text()')[0]
        if movie.xpath('./td[7]/text()'):
            time = movie.xpath('./td[7]/text()')[0]
        else:
            time = ""
        # print(movie_name+' movie_type:'+movie_type+' total:'+total+' person_average:'+price_average+' session_average:'+session_average+' origin:'+origin+' time:'+time)
        info['movie_name'].append(movie_name)
        info['movie_type'].append(movie_type)
        info['total'].append(total)
        info['price_average'].append(price_average)
        info['session_average'].append(session_average)
        info['origin'].append(origin)
        info['time'].append(time)
    return info

3. url构造,获取2008-2019所有榜上的电影信息

urls = ["http://www.cbooo.cn/year?year={}".format(year) for year in range(2008, 2020)]

4. 保存至csv

    用到pandas库,先将字典转成DataFrame,然后直接写入csv即可,可参考我之前的可视化相关的内容.(这里为了显示中文可以在编码方面稍做处理)

def write2csv(dict, year):
    if year == '2008':
        df = pd.DataFrame(data=dict, index=None)
        df.to_csv('box_office.csv', index=False, encoding='gbk', mode='a')
    else:
        df = pd.DataFrame(data=dict, index=None)
        df.to_csv('box_office.csv', index=False, header=False, encoding='gbk', mode='a')

5. csv文件

image.png

可视化

1. 各类型电影总票房数(柱状图)

def draw_bar(filename):
    data = pd.read_csv(filename, encoding='gbk')
    total = data.groupby(data['movie_type'])['total'].sum()
    total.plot(kind='bar')
    plt.legend()

    # 添加网格
    plt.grid(linestyle='--', alpha=0.5)

    plt.xlabel("电影类别")
    plt.ylabel("总票房数量")
    plt.title("各类型电影总票房数")

    plt.show()
image.png

3. 总票房和平均票价的关系(散点图)

def draw_scatter(filename):
    data = pd.read_csv(filename, encoding='gbk')
    plt.title('总票房和平均票价的关系')
    plt.xlabel('平均票价')
    plt.ylabel('总票房(万)')
    plt.scatter(data.price_average, data.total, color='b', linestyle='--', label='上海')
    plt.show()

image.png

3. 剧情类型电影前五票房曲线(折线图)

def draw_plot(filename):
    data = pd.read_csv(filename, encoding='gbk')
    total = data.query('movie_type == "剧情"').head(5).groupby('movie_name')['total'].sum()

    total.plot()
    plt.legend()

    # 添加网格
    plt.grid(linestyle='--', alpha=0.5)

    plt.xlabel("电影")
    plt.ylabel("总票房数量")
    plt.title("剧情类型电影前五票房曲线")

    plt.show()
image.png

4. 电影票房前五的类型分布(饼图)

def draw_pie(filename):
    data = pd.read_csv(filename, encoding='gbk')
    total = data.groupby(data['movie_type'], ).size().sort_values(ascending=False).head(5)
    print(total)
    print(total.index)
    plt.title("电影票房前五的类型分布")
    plt.pie(total, autopct='%.2f%%', labels=total.index)
    plt.axis('equal')
    plt.legend()
    plt.show()
image.png

5. 中文处理

plt.rcParams['font.sans-serif'] = ['Simhei']
  • 更多爬虫代码详情查看Github

你可能感兴趣的:(爬取中国票房网数据并进行可视化)