python爬虫之你好,李焕英电影票房数据分析
一、前言
春节档贺岁片《你好,李焕英》,于2月23日最新数据出来后,票房已经突破42亿,并且赶超其他贺岁片,成为2021的一匹黑马。
从小品演员再到导演,贾玲处女作《你好李焕英》,为何能这么火?接下来荣仔带你运用python借助电影网站从各个角度剖析这部电影喜得高票房的原因。
二、影评爬取并词云分析
毫无疑问, 中国的电影评论伴随着整个社会文化语境的变迁以及不同场域和载体的更迭正发生着明显的变化。在纸质类影评统御了中国电影评论一百年后,又分别出现了电视影评、网络影评、新媒体影评等不同业态相结合的批评话语形式。电影评论的生产与传播确实已经进入一个民主多元化的时代。
电影评论的目的在于分析、鉴定和评价蕴含在银幕中的审美价值、认识价值、社会意义、镜头语等方面,达到拍摄影片的目的,解释影片中所表达的主题,既能通过分析影片的成败得失,帮助导演开阔视野,提高创作水平,以促进电影艺术的繁荣和发展;又能通过分析和评价,影响观众对影片的理解和鉴赏,提高观众的欣赏水平,从而间接促进电影艺术的发展。
2.1 网站选取
python爬虫实战——爬取豆瓣影评数据
2.2 爬取思路
爬取豆瓣影评数据步骤:1、获取网页请求
2、解析获取的网页
3、提取影评数据
4、保存文件
5、词云分析
2.2.1 获取网页请求
该实例选择采用selenium库进行编码。
导库
# 导入库 from selenium import webdriver
浏览器驱动
# 浏览驱动器路径 chromedriver = 'e:/software/chromedriver_win32/chromedriver.exe' driver = webdriver.chrome(chromedriver)
打开网页
driver.get("此处填写网址")
2.2.2解析获取的网页
f12键进入开发者工具,并确定数据提取位置,copy其中的xpath路径
2.2.3提取影评数据
采用xpath进行影评数据提取
driver.find_element_by_xpath('//*[@id="comments"]/div[{}]/div[2]/p/span')
2.2.4保存文件
# 新建文件夹及文件
basepathdirectory = "hudong_coding"
if not os.path.exists(basepathdirectory):
os.makedirs(basepathdirectory)
baidufile = os.path.join(basepathdirectory, "hudongspider.txt")
# 若文件不存在则新建,若存在则追加写入
if not os.path.exists(baidufile):
info = codecs.open(baidufile, 'w', 'utf-8')
else:
info = codecs.open(baidufile, 'a', 'utf-8')
txt文件写入
info.writelines(elem.text + '\r\n')
2.2.5 词云分析
词云分析用到了jieba库和worldcloud库。
值得注意的是,下图显示了文字的选取路径方法。
2.3 代码总观
2.3.1 爬取代码
# -*- coding: utf-8 -*-
# !/usr/bin/env python
import os
import codecs
from selenium import webdriver
# 获取摘要信息
def getfilmreview():
try:
# 新建文件夹及文件
basepathdirectory = "douban_filmreview"
if not os.path.exists(basepathdirectory):
os.makedirs(basepathdirectory)
baidufile = os.path.join(basepathdirectory, "douban_filmreviews.txt")
# 若文件不存在则新建,若存在则追加写入
if not os.path.exists(baidufile):
info = codecs.open(baidufile, 'w', 'utf-8')
else:
info = codecs.open(baidufile, 'a', 'utf-8')
# 浏览驱动器路径
chromedriver = 'e:/software/chromedriver_win32/chromedriver.exe'
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.chrome(chromedriver)
# 打开网页
for k in range(15000): # 大约有15000页
k = k + 1
g = 2 * k
driver.get("https://movie.douban.com/subject/34841067/comments?start={}".format(g))
try:
# 自动搜索
for i in range(21):
elem = driver.find_element_by_xpath('//*[@id="comments"]/div[{}]/div[2]/p/span'.format(i+1))
print(elem.text)
info.writelines(elem.text + '\r\n')
except:
pass
except exception as e:
print('error:', e)
finally:
print('\n')
driver.close()
# 主函数
def main():
print('开始爬取')
getfilmreview()
print('结束爬取')
if __name__ == '__main__':
main()
2.3.2 词云分析代码
# -*- coding: utf-8 -*-
# !/usr/bin/env python
import jieba #中文分词
import wordcloud #绘制词云
# 显示数据
f = open('e:/software/pythonproject/douban_filmreview/douban_filmreviews.txt', encoding='utf-8')
txt = f.read()
txt_list = jieba.lcut(txt)
# print(txt_list)
string = ' '.join((txt_list))
print(string)
# 很据得到的弹幕数据绘制词云图
# mk = imageio.imread(r'图片路径')
w = wordcloud.wordcloud(width=1000,
height=700,
background_color='white',
font_path='c:/windows/fonts/simsun.ttc',
#mask=mk,
scale=15,
stopwords={' '},
contour_width=5,
contour_color='red'
)
w.generate(string)
w.to_file('douban_filmreviews.png')
三、 实时票房搜集
3.1 网站选择
3.2 代码编写
# -*- coding: utf-8 -*-
# !/usr/bin/env python
import os
import time
import datetime
import requests
class pf(object):
def __init__(self):
self.url = 'https://piaofang.maoyan.com/dashboard-ajax?ordertype=0&uuid=173d6dd20a2c8-0559692f1032d2-393e5b09-1fa400-173d6dd20a2c8&risklevel=71&optimuscode=10'
self.headers = {
"referer": "https://piaofang.maoyan.com/dashboard",
"user-agent": "mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/84.0.4147.105 safari/537.36",
}
def main(self):
while true:
# 需在dos命令下运行此文件,才能清屏
os.system('cls')
result_json = self.get_parse()
if not result_json:
break
results = self.parse(result_json)
# 获取时间
calendar = result_json['calendar']['servertimestamp']
t = calendar.split('.')[0].split('t')
t = t[0] + " " + (datetime.datetime.strptime(t[1], "%h:%m:%s") + datetime.timedelta(hours=8)).strftime("%h:%m:%s")
print('北京时间:', t)
x_line = '-' * 155
# 总票房
total_box = result_json['movielist']['data']['nationboxinfo']['nationboxsplitunit']['num']
# 总票房单位
total_box_unit = result_json['movielist']['data']['nationboxinfo']['nationboxsplitunit']['unit']
print(f"今日总票房: {total_box} {total_box_unit}", end=f'\n{x_line}\n')
print('电影名称'.ljust(14), '综合票房'.ljust(11), '票房占比'.ljust(13), '场均上座率'.ljust(11), '场均人次'.ljust(11),'排片场次'.ljust(12),'排片占比'.ljust(12), '累积总票房'.ljust(11), '上映天数', sep='\t', end=f'\n{x_line}\n')
for result in results:
print(
result['moviename'][:10].ljust(9), # 电影名称
result['boxsplitunit'][:8].rjust(10), # 综合票房
result['boxrate'][:8].rjust(13), # 票房占比
result['avgseatview'][:8].rjust(13), # 场均上座率
result['avgshowview'][:8].rjust(13), # 场均人次
result['showcount'][:8].rjust(13), # '排片场次'
result['showcountrate'][:8].rjust(13), # 排片占比
result['sumboxdesc'][:8].rjust(13), # 累积总票房
result['releaseinfo'][:8].rjust(13), # 上映信息
sep='\t', end='\n\n'
)
break
time.sleep(4)
def get_parse(self):
try:
response = requests.get(self.url, headers=self.headers)
if response.status_code == 200:
return response.json()
except requests.connectionerror as e:
print("error:", e)
return none
def parse(self, result_json):
if result_json:
movies = result_json['movielist']['data']['list']
# 场均上座率, 场均人次, 票房占比, 电影名称,
# 上映信息(上映天数), 排片场次, 排片占比, 综合票房,累积总票房
ticks = ['avgseatview', 'avgshowview', 'boxrate', 'moviename',
'releaseinfo', 'showcount', 'showcountrate', 'boxsplitunit', 'sumboxdesc']
for movie in movies:
self.piaofang = {}
for tick in ticks:
# 数字和单位分开需要join
if tick == 'boxsplitunit':
movie[tick] = ''.join([str(i) for i in movie[tick].values()])
# 多层字典嵌套
if tick == 'moviename' or tick == 'releaseinfo':
movie[tick] = movie['movieinfo'][tick]
if movie[tick] == '':
movie[tick] = '此项数据为空'
self.piaofang[tick] = str(movie[tick])
yield self.piaofang
if __name__ == '__main__':
while true:
pf = pf()
pf.main()
3.3 结果展示
四、 剧组照片爬取
4.1 网站选择
4.2 代码编写
# -*- coding: utf-8 -*-
# !/usr/bin/env python
import requests
from bs4 import beautifulsoup
import re
from pil import image
def get_data(url):
# 请求网页
resp = requests.get(url)
# headers 参数确定
headers = {
'user-agent': 'mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/80.0.3987.122 safari/537.36'
}
# 对于获取到的 html 二进制文件进行 'utf-8' 转码成字符串文件
html = resp.content.decode('utf-8')
# beautifulsoup缩小查找范围
soup = beautifulsoup(html, 'html.parser')
# 获取 <a> 的超链接
for link in soup.find_all('a'):
a = link.get('href')
if type(a) == str:
b = re.findall('(.*?)jpg', a)
try:
print(b[0]+'jpg')
img_urls = b[0] + '.jpg'
# 保存数据
for img_url in img_urls:
# 发送图片 url 请求
image = requests.get(img_url, headers=headers).content
# 保存数据
with open(r'e:/images/' + image, 'wb') as img_file:
img_file.write(image)
except:
pass
else:
pass
# 爬取目标网页
if __name__ == '__main__':
get_data('https://www.1905.com/newgallery/hdpic/1495100.shtml')
4.3 效果展示
五、 总结
看这部电影开始笑得有多开心,后面哭得就有多伤心,这部电影用孩子的视角,选取了母亲在选择爱情和婚姻期间所作出的选择,通过对母亲的观察,体会母亲所谓的幸福,并不是贾玲认为的:嫁给厂长的儿子就能获得的,这是他们共同的选择,无论经历过多少次,母亲都会义无反顾选择适合自己的而不是别人认为的那种幸福的人生,这也间接告诉我们:我们追求幸福的过程中,要凭借自己的走,而不是要过别人眼中和口中的幸福,毕竟人生的很多选择只有一次。
到此这篇关于python爬虫之你好,李焕英电影票房数据分析的文章就介绍到这了,更多相关python爬取电影票房内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!