Python爬蟲爬取電影票房資料及圖表展示操作示例
阿新 • • 發佈:2020-03-28
本文例項講述了Python爬蟲爬取電影票房資料及圖表展示操作。分享給大家供大家參考,具體如下:
爬蟲電影歷史票房排行榜 http://www.cbooo.cn/BoxOffice/getInland?pIndex=1&t=0
- Python爬取歷史電影票房紀錄
- 解析Json資料
- 橫向條形圖展示
- 面向物件思想
匯入相關庫
import requests import re from matplotlib import pyplot as plt from matplotlib import font_manager import json
類程式碼部分
class DYOrder(object): #初始化 def __init__(self,page=1): self.url = 'http://www.cbooo.cn/BoxOffice/getInland?pIndex={}&t=0'.format(page) self.headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/76.0.3809.100 Safari/537.36'} #請求 def __to_request(self): response = requests.get(url=self.url,headers=self.headers) return self.__to_parse(response.content.decode('utf-8')) #解析 def __to_parse(self,html): #返回為JSON字串 #首先將字串反序列化為JSON物件 my_json = json.loads(html) return my_json #圖表展示 def __to_show(self,data,show_type): x = [] y = [] for value in data: x.append(value['MovieName']) y.append(int(value['BoxOffice'])) my_font = font_manager.FontProperties(fname='/System/Library/Fonts/PingFang.ttc',size=18) if show_type == 1: plt.figure(figsize=(20,8),dpi=80) rects = plt.bar(range(len(x)),[float(i) for i in y],width=0.5,color='red') plt.xticks(range(len(x)),x,fontproperties=my_font,rotation=60) plt.xlabel('名稱',rotation=60,color='blue',fontproperties=my_font) plt.ylabel('票房/萬',fontproperties=my_font) for rect in rects: height = rect.get_height() plt.text(rect.get_x() + rect.get_width()/2,height+0.4,str(height),ha='center',rotation=30) else: # 橫向 plt.barh(y,x) plt.figure(figsize=(15,13),dpi=80) rects = plt.barh(range(len(x)),y,height=0.8,color='orange') plt.yticks(range(len(x)),rotation=30) plt.ylabel('名稱',rotation=0,fontproperties=my_font) plt.xlabel('票房/萬',fontproperties=my_font) for rect in rects: width = rect.get_width() plt.text(width,rect.get_y()+0.3/2,str(width),va='center',rotation=30) plt.grid(alpha=0.4) plt.title('中國電影歷史票房排行榜',color='red',size=18,fontproperties=my_font) plt.show() #所有操作 def to_run(self,show_type=1): result = self.__to_request() self.__to_show(result,show_type)
呼叫類並展示
if __name__ == '__main__': dy_order = DYOrder(1) # type 1 豎向條形圖 2 橫向 dy_order.to_run(2)
更多關於Python相關內容可檢視本站專題:《Python Socket程式設計技巧總結》、《Python正則表示式用法總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》
希望本文所述對大家Python程式設計有所幫助。