Python爬取豆瓣电影Top250 + 数据可视化
我的这篇博客的一些代码解释python大作业电影演员数据分析
1. 爬取数据
1.1 导入以下模块
import os
import re
import time
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from openpyxl import Workbook, load_workbook
1.2 获取每页电影链接
def getonepagelist(url,headers):
try:
r = requests.get(url, headers=headers, timeout=10)
r.raise_for_status()
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, 'html.parser')
lsts = soup.find_all(attrs={'class': 'hd'})
for lst in lsts:
href = lst.a['href']
time.sleep(0.5)
getfilminfo(href, headers)
except:
print('getonepagelist error!')
1.3 获取每部电影具体信息
def getfilminfo(url,headers):
filminfo = []
r = requests.get(url, headers=headers, timeout=10)
r.raise_for_status()
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, 'html.parser')
1.4 保存数据
def insert2excel(filepath,allinfo):
try:
if not os.path.exists(filepath):
tableTitle = ['片名','上映年份','评分','评价人数','导演','编剧','主演','类型','国家/地区','语言','时长(分钟)']
wb = Workbook()
ws = wb.active
ws.title = 'sheet1'
ws.append(tableTitle)
wb.save(filepath)
time.sleep(3)
wb = load_workbook(filepath)
ws = wb.active
ws.title = 'sheet1'
ws.append(allinfo)
wb.save(filepath)
return True
except:
return False
2. 数据可视化
2.1 导入以下模块
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar
2.2 用pandas模块读取数据
data = pd.read_excel('/home/mw/input/TOP2508837/TOP250.xlsx')
data.head(10)
2.3 各年份上映电影数量柱状图(纵向)
def getzoombar(data):
year_counts = data['上映年份'].value_counts()
year_counts.columns = ['上映年份', '数量']
year_counts = year_counts.sort_index()
c = (
Bar()
.add_xaxis(list(year_counts.index))
.add_yaxis('上映数量', year_counts.values.tolist())
.set_global_opts(
title_opts=opts.TitleOpts(title='各年份上映电影数量'),
yaxis_opts=opts.AxisOpts(name='上映数量'),
xaxis_opts=opts.AxisOpts(name='上映年份'),
datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_='inside')],)
)
2.4 各地区上映电影数量前十柱状图(横向)
def getcountrybar(data):
country_counts = data['国家/地区'].value_counts()
country_counts.columns = ['国家/地区', '数量']
country_counts = country_counts.sort_values(ascending=True)
c = (
Bar()
.add_xaxis(list(country_counts.index)[-10:])
.add_yaxis('地区上映数量', country_counts.values.tolist()[-10:])
.reversal_axis()
.set_global_opts(
title_opts=opts.TitleOpts(title='地区上映电影数量'),
yaxis_opts=opts.AxisOpts(name='国家/地区'),
xaxis_opts=opts.AxisOpts(name='上映数量'),
)
.set_series_opts(label_opts=opts.LabelOpts(position="right"))
)
2.5 电影评价人数前二十柱状图(横向)
def getscorebar(data):
df = data.sort_values(by='评价人数', ascending=True)
c = (
Bar()
.add_xaxis(df['片名'].values.tolist()[-20:])
.add_yaxis('评价人数', df['评价人数'].values.tolist()[-20:])
.reversal_axis()
.set_global_opts(
title_opts=opts.TitleOpts(title='电影评价人数'),
yaxis_opts=opts.AxisOpts(name='片名'),
xaxis_opts=opts.AxisOpts(name='人数'),
datazoom_opts=opts.DataZoomOpts(type_='inside'),
)
.set_series_opts(label_opts=opts.LabelOpts(position="right"))
)