12月已经开始,距离2018年的结束还有半个月的时间,大家还记得年初立下的flag吗?完成了多少?相信很多人和我一样,哭了...这次用猫眼电影来分析2018年的电影大数据1.网页分析01标签通过点击猫眼电影的分类标签,得到URL信息.02索引页打开开发者工具可以在索引页获取电影的链接和评分信息。总共有30多个索引页,但只有10页有电影评级。这次,仅获取具有电影评级的数据。03详情页获取详情页的信息。主要是名称、类型、国家、时长、上映时间、收视率、收视率、累计票房。2、反爬破解通过开发者工具发现,猫眼对收视率、收视率、累计票房数据等数据进行了文字反爬。通过查看网页源代码发现,只要刷新页面,三个文本代码就会发生变化,无法直接匹配到信息。所以你需要下载文本文件并对其进行双重匹配。fromfontTools.ttLibimportTTFont#font=TTFont('base.woff')#font.saveXML('base.xml')font=TTFont('maoyan.woff')font.saveXML('maoyan.xml')将woff格式转xml格式以在Pycharm中查看详细信息。使用以下网站,打开woff文件。url:http://fontstore.baidu.com/static/editor/index.html你可以得到下面数字的信息(上下)。在Pycharm中查看xml格式文件(左右两部分),会找到相应的信息。通过上图,可以将数字6匹配到数字上,其他数字同理。defget_numbers(u):"""对猫眼的文字反爬进行破解"""cmp=re.compile(",\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])breakmaoyan_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)3.数据获取01构造请求头head="""Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Accept-Encoding:gzip,deflate,brAccept-Language:zh-CN,zh;q=0.8Cache-Control:max-age=0Connection:keep-aliveHost:maoyan.comUpgrade-Insecure-请求:1Content-Type:application/x-www-form-urlencoded;charset=UTF-8User-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()返回header_dict,因为索引页和详情页请求头不同,一个函数con为简单起见,此处构造02获取电影详情页链接defget_url():"""获取电影详情页链接"""foriinrange(0,300,30):time.sleep(10)url='http://maoyan.com/films?showType=3&yearId=13&sortId=3&offset='+str(i)host="""Referer:http://maoyan.com/films?showType=3&yearId=13&sortId=3&offset=0"""header=head+hostheaders=str_to_dict(header)response=requests.get(url=url,headers=headers)html=response.textsoup=BeautifulSoup(html,'html.parser')data_1=soup.find_all('div',{'class':'channel-detailmovie-项目标题'})data_2=soup.find_all('div',{'class':'channel-detailchannel-detail-orange'})num=0foritemindata_1:num+=1time.sleep(10)url_1=item.select('a')[0]['href']ifdata_2[num-1].get_text()!='暂无评分':url='http://maoyan.com'+url_1formessageinget_message(url):print(message)to_mysql(message)print(url)print('----------------^^^Film_Message^^^-----------------')else:print('TheWorkIsDone')break03获取电影详情页信息defget_message(url):"""获取电影详情页面信息"""time.sleep(10)data={}host="""refer:http://maoyan.com/news"""header=head+hostheaders=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=['分',分数[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[“人”]=int(浮动(莫viewish))data["box_office"]=bom[2]yielddata4.数据存储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位),***为18446744073709551615INT(10digitsnumber),***为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")db.commit()except:print('Failed')db.rollback()db.close()***成功存储数据5.数据可视化可视化源码就不放了,公众号回复电影可用。01距离电影票房***0还有一个多月的时间。不知道会不会有新成员上榜。《毒液》最近很火,还挺有看头的。02Movierating***0这里不得不吐槽一下pyecharts。坐标转换后,坐标值名称过长会被屏蔽。有待提高~03电影人气***0茫茫人海中,相信一定有我也是其中之一吧!!!04Thenumberofmovieseverymonth每月上映的电影数量似乎没有太大的区别。七月是最少的。是因为天气热吗?厉害,金三银四,金九银十,各行各业的规律,电影业也不例外。上图我们知道7月份的新片数量是最少的,但是票房是第二的。看了这里的资料,发现有《我不是药神》、《西虹市首富》、《恶人昭彰》、《摩天营救》、《救世主》等几部大剧。狄仁杰:四大天王”。06各国电影数量****0原来中国电影多如牛毛,但是豆瓣TOP250中国电影有多少?深思熟虑!!!07中外票房对比2017年全年票房560亿,估计今年很快就会突破。据称,今年全年票房有望突破600亿。08电影名利***0计算公式是将某部电影的评分在所有电影评分中的排名和这部电影的票房在所有电影中的排名相加,然后除以电影总数。除了《侏罗纪世界2》《***》《捉妖记2》,我都看过了!将电影的评级排名相加并除以电影总数。可能是猫眼的用户比较仁慈。与豆瓣相比,总体评分还是比较高的。我个人不敢相信这个结果。但是有一个说的比较准确,就是《爱情公寓》。10部电影类型分布剧情片总是发人深省。感觉今年很多电影都是为了钱,比如《我不是药神》、《西虹市首富》、《好戏》、《头号玩家》。贫穷制约大人物。
