【Python爬蟲(chóng)+數(shù)據(jù)分析】2018年電影,你看了幾部?
12月已開(kāi)始了,離2018年的結(jié)束也就半個(gè)多月的時(shí)間了,還記得年初立下的flag嗎?
完成了多少?相信很多人和我一樣,抱頭痛哭...
本次利用貓眼電影,實(shí)現(xiàn)對(duì)2018年的電影大數(shù)據(jù)進(jìn)行分析。
一、網(wǎng)頁(yè)分析
01 標(biāo)簽
通過(guò)點(diǎn)擊貓眼電影已經(jīng)歸類(lèi)好的標(biāo)簽,得到網(wǎng)址信息。
02 索引頁(yè)
打開(kāi)開(kāi)發(fā)人員工具,獲取索引頁(yè)里電影的鏈接以及評(píng)分信息。
索引頁(yè)一共有30多頁(yè),但是有電影評(píng)分的只有10頁(yè)。
本次只對(duì)有電影評(píng)分的數(shù)據(jù)進(jìn)行獲取。
03 詳情頁(yè)
對(duì)詳情頁(yè)的信息進(jìn)行獲取。
主要是名稱(chēng),類(lèi)型,國(guó)家,時(shí)長(zhǎng),上映時(shí)間,評(píng)分,評(píng)分人數(shù),累計(jì)票房。
二、反爬破解
通過(guò)開(kāi)發(fā)人員工具發(fā)現(xiàn),貓眼針對(duì)評(píng)分,評(píng)分人數(shù),累計(jì)票房的數(shù)據(jù),施加了文字反爬。
通過(guò)查看網(wǎng)頁(yè)源碼,發(fā)現(xiàn)只要刷新頁(yè)面,三處文字編碼就會(huì)改變,無(wú)法直接匹配信息。
所以需要下載文字文件,對(duì)其進(jìn)行雙匹配。
- from fontTools.ttLib import TTFont
- #font = TTFont('base.woff')
- #font.saveXML('base.xml')
- font = TTFont('maoyan.woff')
- font.saveXML('maoyan.xml')
將woff格式轉(zhuǎn)換為xml格式,以便在Pycharm中查看詳細(xì)信息。
利用下面這個(gè)網(wǎng)站,打開(kāi)woff文件。
- url: http://fontstore.baidu.com/static/editor/index.html
可以得到下面數(shù)字部分信息(上下兩塊)。
在Pycharm中查看xml格式文件(左右兩塊),你就會(huì)發(fā)現(xiàn)有對(duì)應(yīng)信息。
通過(guò)上圖你就可以將數(shù)字6對(duì)上號(hào)了,其他數(shù)字一樣的。
- def get_numbers(u):
- """
- 對(duì)貓眼的文字反爬進(jìn)行破解
- """
- cmp = re.compile(",\n url\('(//.*.woff)'\) format\('woff'\)")
- rst = cmp.findall(u)
- ttf = requests.get("http:" + rst[0], stream=True)
- with open("maoyan.woff", "wb") as pdf:
- for chunk in ttf.iter_content(chunk_size=1024):
- if chunk:
- 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']
- for i in range(1, 12):
- maoyan_glyph = maoyanFont['glyf'][maoyan_unicode_list[i]]
- for j in range(11):
- base_glyph = base_font['glyf'][base_unicode_list[j]]
- if maoyan_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") for uni in maoyan_unicode_list[1:]]
- utf8last = []
- for i in range(len(utf8List)):
- utf8List[i] = str(utf8List[i], encoding='utf-8')
- utf8last.append(utf8List[i])
- return (maoyan_num_list ,utf8last)
三、數(shù)據(jù)獲取
01 構(gòu)造請(qǐng)求頭
- 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:maoyan.com
- Upgrade-Insecure-Requests:1
- Content-Type:application/x-www-form-urlencoded; charset=UTF-8
- User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36
- """
- def str_to_dict(header):
- """
- 構(gòu)造請(qǐng)求頭,可以在不同函數(shù)里構(gòu)造不同的請(qǐng)求頭
- """
- header_dict = {}
- header = header.split('\n')
- for h in header:
- h = h.strip()
- if h:
- k, v = h.split(':', 1)
- header_dict[k] = v.strip()
- return header_dict
因?yàn)樗饕?yè)和詳情頁(yè)請(qǐng)求頭不一樣,這里為了簡(jiǎn)便,構(gòu)造了一個(gè)函數(shù)。
02 獲取電影詳情頁(yè)鏈接
- def get_url():
- """
- 獲取電影詳情頁(yè)鏈接
- """
- for i in range(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 + 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-detail movie-item-title'})
- data_2 = soup.find_all('div', {'class': 'channel-detail channel-detail-orange'})
- num = 0
- for item in data_1:
- num += 1
- time.sleep(10)
- url_1 = item.select('a')[0]['href']
- if data_2[num-1].get_text() != '暫無(wú)評(píng)分':
- url = 'http://maoyan.com' + url_1
- for message in get_message(url):
- print(message)
- to_mysql(message)
- print(url)
- print('---------------^^^Film_Message^^^-----------------')
- else:
- print('The Work Is Done')
- break
03 獲取電影詳情頁(yè)信息
- def get_message(url):
- """
- 獲取電影詳情頁(yè)里的信息
- """
- time.sleep(10)
- data = {}
- host = """refer: http://maoyan.com/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]
- # 因?yàn)闀?huì)出現(xiàn)沒(méi)有票房的電影,所以這里需要判斷
- if unit:
- bom = ['分', score[0].get_text().replace('.', '').replace('萬(wàn)', ''), unit[0].get_text()]
- for i in range(len(mw)):
- moviewish = mw[i].get_text().encode('utf-8')
- moviewish = str(moviewish, encoding='utf-8')
- # 通過(guò)比對(duì)獲取反爬文字信息
- for j in range(len(utf8last)):
- moviewish = moviewish.replace(utf8last[j], maoyan_num_list[j])
- if i == 0:
- data["score"] = moviewish + bom[i]
- elif i == 1:
- if '萬(wàn)' in moviewish:
- data["people"] = int(float(moviewish.replace('萬(wàn)', '')) * 10000)
- else:
- data["people"] = int(float(moviewish))
- else:
- if '萬(wàn)' == 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('萬(wàn)', ''), 0]
- for i in range(len(mw)):
- moviewish = mw[i].get_text().encode('utf-8')
- moviewish = str(moviewish, encoding='utf-8')
- for j in range(len(utf8last)):
- moviewish = moviewish.replace(utf8last[j], maoyan_num_list[j])
- if i == 0:
- data["score"] = moviewish + bom[i]
- else:
- if '萬(wàn)' in moviewish:
- data["people"] = int(float(moviewish.replace('萬(wàn)', '')) * 10000)
- else:
- data["people"] = int(float(moviewish))
- data["box_office"] = bom[2]
- yield data
四、數(shù)據(jù)存儲(chǔ)
01 創(chuàng)建數(shù)據(jù)庫(kù)及表格
- db = pymysql.connect(host='127.0.0.1', user='root', password='774110919', port=3306)
- cursor = db.cursor()
- cursor.execute("CREATE DATABASE maoyan DEFAULT CHARACTER SET utf8mb4")
- db.close()
- db = pymysql.connect(host='127.0.0.1', user='root', password='774110919', port=3306, db='maoyan')
- cursor = db.cursor()
- sql = 'CREATE TABLE IF NOT EXISTS films (name VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL, country VARCHAR(255) NOT NULL, length VARCHAR(255) NOT NULL, released VARCHAR(255) NOT NULL, score VARCHAR(255) NOT NULL, people INT NOT NULL, box_office BIGINT NOT NULL, PRIMARY KEY (name))'
- cursor.execute(sql)
- db.close()
其中票房收入數(shù)據(jù)類(lèi)型為BIGINT(19位數(shù)),***為18446744073709551615。
INT(10位數(shù)),***為2147483647,達(dá)不到36億(3600000000)。
02 數(shù)據(jù)存儲(chǔ)
- def to_mysql(data):
- """
- 信息寫(xiě)入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 = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
- try:
- if cursor.execute(sql, tuple(data.values())):
- print("Successful")
- db.commit()
- except:
- print('Failed')
- db.rollback()
- db.close()
***成功存儲(chǔ)數(shù)據(jù)
五、數(shù)據(jù)可視化
可視化源碼就不放了,公眾號(hào)回復(fù)電影即可獲得。
01 電影票房***0
還剩一個(gè)多月,不知道榜單上會(huì)不會(huì)有新成員。最近「毒液」很火,蠻有希望。
02 電影評(píng)分***0
這里就得吐槽一下pyecharts,坐標(biāo)轉(zhuǎn)換后,坐標(biāo)值名稱(chēng)太長(zhǎng)就會(huì)被遮擋,還需改進(jìn)呢~
03 電影人氣***0
茫茫人海之中,相信一定也有大家的身影,我也是其中的一員!!!
04 每月電影上映數(shù)量
每月上映數(shù)好像沒(méi)什么大差距,7月最少,難道是因?yàn)樘鞖鉄?
05 每月電影票房
這里就看出春節(jié)檔電影的威力了,金三銀四、金九銀十,各行各業(yè)的規(guī)律,電影行業(yè)也不例外。
上一張圖我們知道7月份電影上新最少,票房反而是第二。
這里看了下數(shù)據(jù),發(fā)現(xiàn)有「我不是藥神」「西虹市首富」「邪不壓正」「摩天營(yíng)救」「狄仁杰之四大天王」幾部大劇撐著。
06 各國(guó)家電影數(shù)量***0
原來(lái)中國(guó)電影這么高產(chǎn)的,可是豆瓣TOP250里又有多少中國(guó)電影呢?深思!!!
07 中外票房對(duì)比
2017年的年度票房是560億,估計(jì)今年快要突破了。據(jù)說(shuō)今年全年票房有望突破600億。
08 電影名利雙收***0
計(jì)算公式是,把某部電影的評(píng)分在所有電影評(píng)分中的排名與這部電影的票房在所有票房中的排名加起來(lái),再除以電影總數(shù)。
除了「侏羅紀(jì)世界2」「***」「捉妖記2」,我都看過(guò)啦!
09 電影叫座不叫好***0
計(jì)算公式是,把某部電影的票房排名減去某部電影的評(píng)分排名加起來(lái),再除以電影總數(shù)。
可能是貓眼的用戶(hù)比較仁慈吧,與豆瓣相比,普遍評(píng)分都比較高。我個(gè)人都不太敢相信這個(gè)結(jié)果。
不過(guò)有一個(gè)還是挺準(zhǔn)的,「愛(ài)情公寓」。
10 電影類(lèi)型分布
劇情電影永遠(yuǎn)引人深思。感覺(jué)今年的電影好多跟錢(qián)有關(guān),比如「我不是藥神」「西虹市首富」「一出好戲」「頭號(hào)玩家」,貧窮限制了大家伙們。