阅读文本大概需要 18 分钟。
双11已经过去,双12即将来临,离的结束也就2个月不到,还记得年初立下的flag吗?
完成了多少?相信很多人和我一样,抱头痛哭...
本次利用猫眼电影,实现对的电影大数据进行分析。
/ 01 / 网页分析
01 标签
通过点击猫眼电影已经归类好的标签,得到网址信息。
02 索引页
打开开发人员工具,获取索引页里电影的链接以及评分信息。
索引页一共有30多页,但是有电影评分的只有10页。
本次只对有电影评分的数据进行获取。
03 详情页
对详情页的信息进行获取。
主要是名称,类型,国家,时长,上映时间,评分,评分人数,累计票房。
/ 02 / 反爬破解
通过开发人员工具发现,猫眼针对评分,评分人数,累计票房的数据,施加了文字反爬。
通过查看网页源码,发现只要刷新页面,三处文字编码就会改变,无法直接匹配信息。
所以需要下载文字文件,对其进行双匹配。
fromfontTools.ttLibimportTTFont
#font=TTFont('base.woff')
#font.saveXML('base.xml')
font=TTFont('maoyan.woff')
font.saveXML('maoyan.xml')
将woff格式转换为xml格式,以便在Pycharm中查看详细信息。
利用下面这个网站,打开woff文件。
url:/static/editor/index.html
可以得到下面数字部分信息(上下两块)。
在Pycharm中查看xml格式文件(左右两块),你就会发现有对应信息。
通过上图你就可以将数字6对上号了,其他数字一样的。
defget_numbers(u):
"""
对猫眼的文字反爬进行破解
"""
cmp=pile(",\nurl\('(//.*.woff)'\)format\('woff'\)")
rst=cmp.findall(u)
ttf=requests.get("http:"+rst[0],stream=True)
withopen("maoyan.woff","wb")aspdf:
forchunkinttf.iter_content(chunk_size=1024):
ifchunk:
pdf.write(chunk)
base_font=TTFont('base.woff')
maoyanFont=TTFont('maoyan.woff')
maoyan_unicode_list=maoyanFont['cmap'].tables[0].ttFont.getGlyphOrder()
maoyan_num_list=[]
base_num_list=['.','3','0','8','9','4','1','5','2','7','6']
base_unicode_list=['x','uniF561','uniE6E1','uniF125','uniF83F','uniE9E2','uniEEA6','uniEEC2','uniED38','uniE538','uniF8E7']
foriinrange(1,12):
maoyan_glyph=maoyanFont['glyf'][maoyan_unicode_list[i]]
forjinrange(11):
base_glyph=base_font['glyf'][base_unicode_list[j]]
ifmaoyan_glyph==base_glyph:
maoyan_num_list.append(base_num_list[j])
break
maoyan_unicode_list[1]='uni0078'
utf8List=[eval(r"'\u"+uni[3:]+"'").encode("utf-8")foruniinmaoyan_unicode_list[1:]]
utf8last=[]
foriinrange(len(utf8List)):
utf8List[i]=str(utf8List[i],encoding='utf-8')
utf8last.append(utf8List[i])
return(maoyan_num_list ,utf8last)
/ 03 / 数据获取
01 构造请求头
head="""
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip,deflate,br
Accept-Language:zh-CN,zh;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:
Upgrade-Insecure-Requests:1
Content-Type:application/x-www-form-urlencoded;charset=UTF-8
User-Agent:Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/59.0.3071.86Safari/537.36
"""
defstr_to_dict(header):
"""
构造请求头,可以在不同函数里构造不同的请求头
"""
header_dict={}
header=header.split('\n')
forhinheader:
h=h.strip()
ifh:
k,v=h.split(':',1)
header_dict[k]=v.strip()
returnheader_dict
因为索引页和详情页请求头不一样,这里为了简便,构造了一个函数。
02 获取电影详情页链接
defget_url():
"""
获取电影详情页链接
"""
foriinrange(0,300,30):
time.sleep(10)
url='/films?showType=3&yearId=13&sortId=3&offset='+str(i)
host="""Referer:/films?showType=3&yearId=13&sortId=3&offset=0
"""
header=head+host
headers=str_to_dict(header)
response=requests.get(url=url,headers=headers)
html=response.text
soup=BeautifulSoup(html,'html.parser')
data_1=soup.find_all('div',{'class':'channel-detailmovie-item-title'})
data_2=soup.find_all('div',{'class':'channel-detailchannel-detail-orange'})
num=0
foritemindata_1:
num+=1
time.sleep(10)
url_1=item.select('a')[0]['href']
ifdata_2[num-1].get_text()!='暂无评分':
url=''+url_1
formessageinget_message(url):
print(message)
to_mysql(message)
print(url)
print('---------------^^^Film_Message^^^-----------------')
else:
print('TheWorkIsDone')
break
03 获取电影详情页信息
defget_message(url):
"""
获取电影详情页里的信息
"""
time.sleep(10)
data={}
host="""refer:/news
"""
header=head+host
headers=str_to_dict(header)
response=requests.get(url=url,headers=headers)
u=response.text
#破解猫眼文字反爬
(mao_num_list, utf8last)=get_numbers(u)
#获取电影信息
soup=BeautifulSoup(u,"html.parser")
mw=soup.find_all('span',{'class':'stonefont'})
score=soup.find_all('span',{'class':'score-num'})
unit=soup.find_all('span',{'class':'unit'})
ell=soup.find_all('li',{'class':'ellipsis'})
name=soup.find_all('h3',{'class':'name'})
#返回电影信息
data["name"]=name[0].get_text()
data["type"]=ell[0].get_text()
data["country"]=ell[1].get_text().split('/')[0].strip().replace('\n','')
data["length"]=ell[1].get_text().split('/')[1].strip().replace('\n','')
data["released"]=ell[2].get_text()[:10]
#因为会出现没有票房的电影,所以这里需要判断
ifunit:
bom=['分',score[0].get_text().replace('.','').replace('万',''),unit[0].get_text()]
foriinrange(len(mw)):
moviewish=mw[i].get_text().encode('utf-8')
moviewish=str(moviewish,encoding='utf-8')
#通过比对获取反爬文字信息
forjinrange(len(utf8last)):
moviewish=moviewish.replace(utf8last[j],maoyan_num_list[j])
ifi==0:
data["score"]=moviewish+bom[i]
elifi==1:
if'万'inmoviewish:
data["people"]=int(float(moviewish.replace('万',''))*10000)
else:
data["people"]=int(float(moviewish))
else:
if'万'==bom[i]:
data["box_office"]=int(float(moviewish)*10000)
else:
data["box_office"]=int(float(moviewish)*100000000)
else:
bom=['分',score[0].get_text().replace('.','').replace('万',''),0]
foriinrange(len(mw)):
moviewish=mw[i].get_text().encode('utf-8')
moviewish=str(moviewish,encoding='utf-8')
forjinrange(len(utf8last)):
moviewish=moviewish.replace(utf8last[j],maoyan_num_list[j])
ifi==0:
data["score"]=moviewish+bom[i]
else:
if'万'inmoviewish:
data["people"]=int(float(moviewish.replace('万',''))*10000)
else:
data["people"]=int(float(moviewish))
data["box_office"]=bom[2]
yielddata
/ 04 / 数据存储
01 创建数据库及表格
db=pymysql.connect(host='127.0.0.1',user='root',password='774110919',port=3306)
cursor=db.cursor()
cursor.execute("CREATEDATABASEmaoyanDEFAULTCHARACTERSETutf8mb4")
db.close()
db=pymysql.connect(host='127.0.0.1',user='root',password='774110919',port=3306,db='maoyan')
cursor=db.cursor()
sql='CREATETABLEIFNOTEXISTSfilms(nameVARCHAR(255)NOTNULL,typeVARCHAR(255)NOTNULL,countryVARCHAR(255)NOTNULL,lengthVARCHAR(255)NOTNULL,releasedVARCHAR(255)NOTNULL,scoreVARCHAR(255)NOTNULL,peopleINTNOTNULL,box_officeBIGINTNOTNULL,PRIMARYKEY(name))'
cursor.execute(sql)
db.close()
其中票房收入数据类型为BIGINT(19位数),最大为18446744073709551615。
INT(10位数),最大为2147483647,达不到36亿(3600000000)。
02 数据存储
defto_mysql(data):
"""
信息写入mysql
"""
table='films'
keys=','.join(data.keys())
values=','.join(['%s']*len(data))
db=pymysql.connect(host='localhost',user='root',password='774110919',port=3306,db='maoyan')
cursor=db.cursor()
sql='INSERTINTO{table}({keys})VALUES({values})'.format(table=table,keys=keys,values=values)
try:
ifcursor.execute(sql,tuple(data.values())):
print("Successful")
mit()
except:
print('Failed')
db.rollback()
db.close()
最后成功存储数据
/ 05 / 数据可视化
可视化源码就不放了,公众号回复电影即可获得。
01 电影票房TOP10
还剩一个多月,不知道榜单上会不会有新成员。最近「毒液」很火,蛮有希望。
02 电影评分TOP10
这里就得吐槽一下pyecharts,坐标转换后,坐标值名称太长就会被遮挡,还需改进呢~
03 电影人气TOP10
茫茫人海之中,相信一定也有大家的身影,我也是其中的一员!!!
04 每月电影上映数量
每月上映数好像没什么大差距,7月最少,难道是因为天气热?
05 每月电影票房
这里就看出春节档电影的威力了,金三银四、金九银十,各行各业的规律,电影行业也不例外。
上一张图我们知道7月份电影上新最少,票房反而是第二。
这里看了下数据,发现有「我不是药神」「西虹市首富」「邪不压正」「摩天营救」「狄仁杰之四大天王」几部大剧撑着。
06 各国家电影数量TOP10
原来中国电影这么高产的,可是豆瓣 TOP250 里又有多少中国电影呢?深思!!!
07 中外票房对比
年的年度票房是 560 亿,估计今年快要突破了。据说今年全年票房有望突破 600 亿。
08 电影名利双收TOP10
计算公式是,把某部电影的评分在所有电影评分中的排名与这部电影的票房在所有票房中的排名加起来,再除以电影总数。
除了「侏罗纪世界2」「无双」「捉妖记2」,我都看过啦!
09 电影叫座不叫好TOP10
计算公式是,把某部电影的票房排名减去某部电影的评分排名加起来,再除以电影总数。
可能是猫眼的用户比较仁慈吧,与豆瓣相比,普遍评分都比较高。我个人都不太敢相信这个结果。
不过有一个还是挺准的,「爱情公寓」。
10 电影类型分布
剧情电影永远引人深思。感觉今年的电影好多跟钱有关,比如「我不是药神」「西虹市首富」「一出好戏」「头号玩家」,贫穷限制了大家伙们。
公众号回复电影。即可获取全部源码。
现在微信改版了
好多人跟痴海说
看不到痴海了
其实只要把痴海置顶就可以了
只需要5秒钟
痴海教你置顶
推荐阅读: