1. 程式人生 > >資料分析?小意思!python幫你搞定

資料分析?小意思!python幫你搞定

資料分析?小意思!python幫你搞定

 

前言

如果大家經常閱讀Python爬蟲相關的公眾號,都會是以爬蟲+資料分析的形式展現的,這樣很有趣,圖表也很不錯,今天了,我就來分享上一次在培訓中的一個作品:貓眼電影爬蟲及分析。

通過貓眼電影TOP100榜的爬蟲,然後進行視覺化,讓學員體會到,小資料爬蟲也能玩出這樣的花樣來。

爬蟲

爬蟲分析

這裡是獲取的是top100的電影資料,進行了跨頁爬蟲,獲取的欄位:電影名,主演,上映時間,評分,電影型別和時長。最後儲存在csv檔案中。

爬蟲程式碼

import requests
from lxml import etree
import csv
headers = {
 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
def get_url(url):
 res = requests.get(url,headers=headers)
 html = etree.HTML(res.text)
 infos = html.xpath('//dl[@class="board-wrapper"]/dd')
 for info in infos:
 name = info.xpath('div/div/div[1]/p[1]/a/text()')[0]
 info_url = 'http://maoyan.com' + info.xpath('div/div/div[1]/p[1]/a/@href')[0]
 star = info.xpath('div/div/div[1]/p[2]/text()')[0].strip()
 release_time = info.xpath('div/div/div[1]/p[3]/text()')[0].strip()
 score_1 = info.xpath('div/div/div[2]/p/i[1]/text()')[0]
 score_2 = info.xpath('div/div/div[2]/p/i[2]/text()')[0]
 score = score_1 + score_2
 # print(name,star,release_time,score,info_url)
 get_info(info_url,name,star,release_time,score)
def get_info(url,name,star,time,score):
 res = requests.get(url, headers=headers)
 html = etree.HTML(res.text)
 style = html.xpath('/html/body/div[3]/div/div[2]/div[1]/ul/li[1]/text()')[0]
 long_time = html.xpath('/html/body/div[3]/div/div[2]/div[1]/ul/li[2]/text()')[0].split('/')[1].strip()
 print(name,star,time,score,style,long_time)
 writer.writerow([name,star,time,score,style,long_time])
if __name__ == '__main__':
 fp = open('maoyan_2.csv','w',encoding='utf-8',newline='')
 writer = csv.writer(fp)
 writer.writerow(['name','star','time','score','style','long_time'])
 urls = ['http://maoyan.com/board/4?offset={}'.format(str(i)) for i in range(0, 100, 10)]
 for url in urls:
 get_url(url)

資料分析?小意思!python幫你搞定

 

資料分析

資料分析我做成了PPT的樣子,大家可以看看~

總體情況

100部電影,平均得分9.0,平均電影時長128.63。

資料分析?小意思!python幫你搞定

 

電影年份趨勢

電影年份趨勢不大,規律不太明顯。

資料分析?小意思!python幫你搞定

 

電影月份

大家看電影都知道,電影基本在假期上映更有熱度,這裡統計出來,發現下半年的電影比上半年電影好很多~

資料分析?小意思!python幫你搞定

 

地區

中國和美國還是佔了很多的,韓國和日本電影也很不錯~

資料分析?小意思!python幫你搞定

 

電影型別

電影大部分都是劇情的,愛情才是真諦啊。

資料分析?小意思!python幫你搞定

 

演員

小哥和星爺承載了我們的清楚呀~

資料分析?小意思!python幫你搞定

 

總結

別看這小小的100條資料,是不是也可以玩出不一樣的花樣來。